Overview
A raw waveform is thousands of samples per second, and no single sample says much. Features summarize short stretches of it in a few numbers that mean something. The signal is cut into overlapping frames of a few tens of milliseconds, and each frame is described from several angles: how its energy is spread across frequency, which musical notes are sounding, how loud it is, and whether something new just started. All features use the same frames, so they line up row by row and can be stacked into one table for a model. This template is a compact version of what audio libraries provide, without extras such as pre-emphasis or delta features.
A short history
Compact audio features grew out of speech research. Stevens, Volkmann and Newman proposed the mel scale of perceived pitch in 1937. In 1980 Steven Davis and Paul Mermelstein showed that mel-frequency cepstral coefficients beat other features for word recognition, and MFCCs became the standard input of speech recognisers for decades. Chroma, spectral centroid and onset features were added later by music information retrieval research.
How it works
- Cut the signal into frames of n_fft samples, each starting hop_length samples after the previous one.
- Multiply each frame by a Hann window and take the squared magnitude of its Fourier transform. This is the power spectrum of the frame.
- For MFCCs, pool the power into bands spaced evenly on the mel scale, take the logarithm, and apply a discrete cosine transform. Keep the first n_mfcc coefficients.
- For chroma, assign each frequency bin to its nearest musical note, fold all octaves together into 12 pitch classes, and scale each frame so its largest entry is 1.
- For the spectral centroid, take the power-weighted average frequency of the frame.
- For level and noisiness, compute the root mean square of the samples and the share of neighbouring samples that change sign.
- For onsets, add up how much the log energy of each mel band rose since the previous frame, and mark the peaks of that curve as event starts.
Watch out for
- With the default 512-sample frame at 16 kHz, frequency bins are 31.25 Hz apart. Below roughly 500 Hz neighbouring notes are closer than that, so chroma cannot separate them.
- MFCCs discard pitch and fine spectral detail by design. They suit speech and timbre tasks and are a poor choice when the note itself matters.
- Coefficient 0 of the MFCC mostly tracks loudness. Leaving it in makes a model sensitive to recording level.
- Zero-crossing rate is fragile: a small constant offset or low hum in the signal changes it completely.
- Features depend on sample_rate, n_fft and hop_length. A model trained on one setting sees different numbers under another, so fix the settings and store them with the model.
Use cases
When to use it
Preparing audio, vibration or other oscillating signals for a classical model or a small neural network, and when you want inputs whose meaning you can inspect.
In industry
- Speech technology
- Speech and speaker recognisers long used MFCC vectors per frame as input, and many small on-device models still do.
- Music streaming
- Music analysis systems use chroma for key and chord estimation and onset strength for tempo and beat tracking.
- Industrial monitoring
- Predictive maintenance systems compute level, centroid and band energies from vibration or sound to flag a failing bearing or motor.
Choosing it: what must hold
- A sampled one-dimensional signal with a known sample rate, such as audio or vibration.
- A signal that is roughly steady within one short frame, so per-frame numbers are meaningful.
- A downstream model that benefits from a small, fixed set of numbers per frame, for example a classical classifier or a small data set.
When to choose something else
| If | Use instead |
|---|---|
| You have a lot of labelled data and train a deep network | Spectral analysis: feed log-mel spectrograms, or let the network learn from the waveform |
| You only need the frequency content of the whole signal | Fourier transforms |
| Events are brief and need precise placement in time and scale | Wavelets |
Math foundations
Power spectrum of a frame
Frame starts at sample . It is multiplied by the window and transformed, and the squared magnitude says how much energy sits at bin , which is frequency .
The mel scale
A frequency axis that follows hearing: roughly linear below 1 kHz and logarithmic above. Mel bands are triangles spaced evenly on this axis, so they are narrow at low frequencies and wide at high ones.
MFCC
A discrete cosine transform of the log mel energies . Low coefficients describe the broad shape of the spectrum and high ones the fine ripple, so keeping the first few gives a compact, decorrelated description of timbre.
Pitch class of a frequency
The first part is the MIDI note number: 69 is the A at 440 Hz and each doubling of frequency adds 12. Taking the remainder modulo 12 drops the octave, leaving one of the classes C, C sharp, up to B.
Spectral centroid
The centre of mass of the spectrum in Hz. Bright, hissy sounds have a high centroid and dull ones a low centroid.
RMS level
The root of the mean squared sample value of the frame. A sine of amplitude has an RMS of .
Onset strength
Spectral flux: the total rise in log band energy from one frame to the next. Falls are ignored, so the start of a note gives a peak and its decay does not.
Symbols
- the signal at sample
- the Hann window
- the frame length and FFT size (n_fft)
- the hop between frames in samples (hop_length)
- the frame index and the frequency bin index
- the imaginary unit
- the sample rate in Hz
- a frequency in Hz, and the frequency of bin
- the power of frame at bin
- the energy of frame in mel band
- the number of mel bands (n_mels)
- MFCC number of frame
- the spectral centroid of frame
- the onset strength at frame
Worked by hand
Find the pitch class of middle C at 261.63 Hz, the mel value of 1000 Hz, and the zero-crossing rate of a 440 Hz sine sampled at 16 kHz.
Class 0 is C, as expected. The mel scale is built so that 1000 Hz maps to about 1000 mels. A sine crosses zero twice per cycle, so 5.5% of neighbouring sample pairs change sign.
Visual example
Loading the example.
Try this
- Click Chroma and change the melody: the bright row moves from note to note.
- Click Power spectrum and raise the overtones. The centroid line climbs although the notes have not changed.
- Choose the same C four times and click Onset strength: chroma is flat, yet four starts are found.
Code sample
import numpy as np
from impl import FeatureExtractor
from config import FeatureExtractorConfig
sr = 16000
t = np.arange(sr) / sr
x = np.where(t >= 0.5, np.sin(2 * np.pi * 880 * t), 0.0) # silence, then an A5 from 0.5 s
fx = FeatureExtractor(FeatureExtractorConfig(sample_rate=sr))
feats = fx.extract(x) # dict of arrays with 97 rows
feats["mfcc"].shape # (97, 13)
feats["chroma"][-1].argmax() # 9, the pitch class A
fx.detect_onsets(x) # one onset near 0.5 sRead the implementation (154 lines)
"""Frame-level features of an audio-like signal.
Timbre: MFCC and spectral centroid. Pitch content: 12-bin chroma. Rhythm: onset strength (spectral flux) and
onset times. Level and noisiness: RMS energy and zero-crossing rate. Every feature is computed on the same
frames, so the rows of all outputs line up and can be stacked into one feature matrix.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import FeatureExtractorConfig
except ImportError: # run from the template's own folder
from config import FeatureExtractorConfig
PITCH_CLASSES = ("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
MIN_ONSET_STRENGTH = 1.0 # summed rise of log mel energy; 1.0 is an e-fold jump in a single band
class FeatureExtractor:
"""Per-frame features. Frame i covers samples i * hop_length .. i * hop_length + n_fft - 1."""
def __init__(self, config: FeatureExtractorConfig | None = None) -> None:
self.config = config or FeatureExtractorConfig()
n = self.config.n_fft
self.window = 0.5 - 0.5 * np.cos(2.0 * np.pi * np.arange(n) / n) # periodic Hann
self.freqs = np.arange(n // 2 + 1) * self.config.sample_rate / n
def frames(self, x) -> np.ndarray:
"""Cut x, array (n,), into frames, array (n_frames, n_fft). A signal shorter than one frame is zero-padded."""
x = np.asarray(x, dtype=float).ravel()
n, hop = self.config.n_fft, self.config.hop_length
if x.size < n:
x = np.concatenate([x, np.zeros(n - x.size)])
count = 1 + (x.size - n) // hop
return x[np.arange(n)[None, :] + hop * np.arange(count)[:, None]]
def frame_times(self, n_frames: int) -> np.ndarray:
"""Time in seconds of the centre of each frame, array (n_frames,)."""
return (np.arange(n_frames) * self.config.hop_length + self.config.n_fft / 2.0) / self.config.sample_rate
def power_spectrogram(self, x) -> np.ndarray:
"""Squared magnitude of the windowed FFT of each frame. Returns array (n_frames, n_fft // 2 + 1)."""
return np.abs(np.fft.rfft(self.frames(x) * self.window, axis=1)) ** 2
def mel_filterbank(self) -> np.ndarray:
"""Triangular filters equally spaced on the mel scale from 0 Hz to Nyquist. Returns array (n_mels, n_bins)."""
def to_mel(f):
return 2595.0 * np.log10(1.0 + f / 700.0)
top = to_mel(self.config.sample_rate / 2.0)
edges = 700.0 * (10.0 ** (np.linspace(0.0, top, self.config.n_mels + 2) / 2595.0) - 1.0)
f = self.freqs[None, :]
rising = (f - edges[:-2, None]) / (edges[1:-1, None] - edges[:-2, None])
falling = (edges[2:, None] - f) / (edges[2:, None] - edges[1:-1, None])
return np.maximum(0.0, np.minimum(rising, falling))
def log_mel(self, x) -> np.ndarray:
"""Log of the mel-band energies. Returns array (n_frames, n_mels)."""
return np.log(self.power_spectrogram(x) @ self.mel_filterbank().T + 1e-6)
def mfcc(self, x) -> np.ndarray:
"""Mel-frequency cepstral coefficients: orthonormal DCT-II of the log mel energies.
Returns array (n_frames, n_mfcc). Coefficient 0 tracks overall level, the others the shape of the spectrum.
"""
n = self.config.n_mels
k = np.arange(self.config.n_mfcc)[:, None]
basis = np.cos(np.pi * k * (np.arange(n)[None, :] + 0.5) / n) * math.sqrt(2.0 / n)
basis[0] /= math.sqrt(2.0)
return self.log_mel(x) @ basis.T
def chroma(self, x) -> np.ndarray:
"""Energy per pitch class (C, C#, ..., B), all octaves folded together. Returns array (n_frames, 12).
Each FFT bin from 27.5 Hz up is assigned to the nearest equal-tempered note (A4 = 440 Hz). Each frame is
scaled so its largest entry is 1; silent frames stay zero.
"""
power = self.power_spectrogram(x)
usable = self.freqs >= 27.5
midi = 69.0 + 12.0 * np.log2(self.freqs[usable] / 440.0)
pitch_class = np.round(midi).astype(int) % 12
out = np.zeros((power.shape[0], 12))
for c in range(12):
out[:, c] = power[:, usable][:, pitch_class == c].sum(axis=1)
peak = out.max(axis=1, keepdims=True)
return np.divide(out, peak, out=np.zeros_like(out), where=peak > 0)
def spectral_centroid(self, x) -> np.ndarray:
"""Power-weighted mean frequency of each frame in Hz, array (n_frames,). Higher means brighter. 0 for silence."""
power = self.power_spectrogram(x)
total = power.sum(axis=1)
return np.divide(power @ self.freqs, total, out=np.zeros_like(total), where=total > 0)
def rms(self, x) -> np.ndarray:
"""Root mean square level of each frame, array (n_frames,)."""
return np.sqrt(np.mean(self.frames(x) ** 2, axis=1))
def zero_crossing_rate(self, x) -> np.ndarray:
"""Share of consecutive sample pairs in each frame whose signs differ, array (n_frames,).
A sine of frequency f gives 2 f / sample_rate; noise gives about 0.5.
"""
positive = self.frames(x) >= 0
return np.mean(positive[:, 1:] != positive[:, :-1], axis=1)
def onset_strength(self, x) -> np.ndarray:
"""Spectral flux: the summed increase of log mel energy from one frame to the next, array (n_frames,).
Only increases count, so a note starting gives a peak and a steady or fading one does not. Energies
more than 40 dB below the loudest band of the whole signal are clipped to that floor first, so the
result does not depend on the overall level and near-silent bands cannot add ripple. The first frame is 0.
"""
mel = self.power_spectrogram(x) @ self.mel_filterbank().T
if mel.max() <= 0:
return np.zeros(mel.shape[0])
log_mel = np.log(np.maximum(mel, 1e-4 * mel.max()))
rise = np.maximum(0.0, np.diff(log_mel, axis=0)).sum(axis=1)
return np.concatenate([[0.0], rise])
def detect_onsets(self, x) -> np.ndarray:
"""Times in seconds at which new events start. Returns a 1-D array, possibly empty.
An onset is a local maximum of the onset strength above onset_threshold times its largest value. Of two
peaks closer than one frame length, only the stronger is kept. Peaks weaker than MIN_ONSET_STRENGTH
(the ripple of a steady sound) are ignored, so a signal without events returns nothing.
"""
strength = self.onset_strength(x)
if strength.max() < MIN_ONSET_STRENGTH:
return np.zeros(0)
s = strength / strength.max()
peaks = [i for i in range(1, s.size) if s[i] >= self.config.onset_threshold and s[i] > s[i - 1]
and (i + 1 == s.size or s[i] >= s[i + 1]) and strength[i] >= MIN_ONSET_STRENGTH]
min_gap = self.config.n_fft // self.config.hop_length + 1
kept: list[int] = []
for i in peaks:
if kept and i - kept[-1] < min_gap:
if s[i] > s[kept[-1]]:
kept[-1] = i
else:
kept.append(i)
return self.frame_times(s.size)[kept]
def extract(self, x) -> dict:
"""All per-frame features in one dict of arrays that share their first dimension (n_frames)."""
return {
"mfcc": self.mfcc(x),
"chroma": self.chroma(x),
"spectral_centroid": self.spectral_centroid(x),
"rms": self.rms(x),
"zero_crossing_rate": self.zero_crossing_rate(x),
"onset_strength": self.onset_strength(x),
}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Make one second of a 440 Hz sine at 16 kHz and pass it to FeatureExtractor().extract. Check that the chroma column for A (index 9 in PITCH_CLASSES) is the largest, that spectral_centroid is near 440 and that zero_crossing_rate is near 0.055. Then build a signal of silence with three short noise bursts and compare detect_onsets with the burst times you chose.
Check on learning
- Why take the logarithm of the mel energies before the cosine transform?
A way to think about it
Think about how loudness is perceived and about what a change of recording gain does to the energies, before and after a logarithm.
- Doubling n_fft halves the spacing between frequency bins. What do you lose in exchange, and which of these features suffers?
A way to think about it
A longer frame averages over more time. Ask what happens to the sharpness of an onset when each frame spans twice as long.
- A sine and white noise can have the same RMS. Which two features here tell them apart, and how?
A way to think about it
One concentrates all its energy in a single bin and crosses zero at a fixed rate. Consider the centroid and the zero-crossing rate of each.
- The onset strength counts only increases in band energy. What would go wrong if decreases were counted too?
A way to think about it
Picture a single note that starts and then stops. Count how many events each version of the measure would report.
- Chroma folds all octaves together. For which tasks is that an advantage and for which is it a loss?
A way to think about it
Compare recognizing a chord regardless of how it is voiced with telling a bass line from a melody.