Overview
One Fourier transform of a whole recording tells you which frequencies occurred, but not when. The short-time Fourier transform, or STFT, fixes that by sliding a short window along the signal and transforming each piece on its own. Stacking the results gives a picture with time on one axis and frequency on the other, the spectrogram. From there, pooling the frequency bins into bands spaced the way hearing works gives the mel spectrogram, and compressing those bands with a cosine transform gives the MFCCs. Averaging the frame spectra over time, as Welch's method does, gives a steady estimate of how the signal's power is spread across frequency.
A short history
The sound spectrograph was built at Bell Labs in the 1940s and showed speech as a picture of frequency against time. Dennis Gabor gave the mathematical basis in 1946 by analysing signals in short windowed pieces. Digital versions followed the fast Fourier transform in the 1960s. The mel scale dates from 1937 and MFCCs from Davis and Mermelstein in 1980. Log-mel spectrograms are now the usual input of neural speech and audio models.
How it works
- Choose a frame length n_fft and a hop_length. With center on, the signal is padded by reflection so that frame is centred on sample times the hop.
- Multiply each frame by a window (Hann by default) so its ends fade to zero.
- Take the FFT of each windowed frame and keep the non-negative frequencies. The result is a complex matrix of frames by bins: the STFT.
- Square the magnitudes to get the power spectrogram.
- Multiply by a bank of triangular filters spaced evenly on the mel scale to get the mel spectrogram.
- Take the log and apply a discrete cosine transform to get MFCCs, keeping the first n_mfcc coefficients.
- To go back to a waveform, inverse-transform each frame, window it again, add the overlapping frames and divide by the summed squared windows.
Watch out for
- Time and frequency resolution trade off. A long frame separates close frequencies but smears events in time, and a short one does the reverse. No setting gives both.
- The spectrogram discards phase. A magnitude or mel spectrogram cannot be inverted exactly, and istft needs the full complex STFT.
- Exact inversion needs enough overlap. A Hann window with a hop of a quarter frame works, while a hop equal to the frame length leaves points where the window is zero.
- The logarithm of a near-zero energy is a large negative number, so silent frames can dominate a model's input range. The template adds a small constant before the log.
- Mel bands are wide at high frequencies. Two tones that are clearly separate in the spectrogram can fall into the same band.
Use cases
When to use it
Speech, music and any signal whose character changes over time. Mel spectrograms are the standard input of audio neural networks, and Welch's estimate is the standard way to measure a noise spectrum.
In industry
- Speech recognition
- Models such as Whisper take log-mel spectrograms of the audio as input instead of the raw waveform.
- Music identification
- Audio fingerprinting services such as Shazam match a recording by the pattern of peaks in its spectrogram.
- Bioacoustics
- Researchers detect bird and whale calls by reading or classifying spectrograms of long field recordings.
- Condition monitoring
- Engineers track how a machine's vibration frequencies shift during run-up with a spectrogram.
Choosing it: what must hold
- A sampled signal whose frequency content changes over time.
- A frame length chosen for the task: longer frames resolve frequency better, shorter frames resolve time better.
- A window and hop size that overlap enough, especially if the signal must be rebuilt from the frames.
- For mel and MFCC views, a signal where a perceptual frequency scale makes sense, such as speech or music.
When to choose something else
| If | Use instead |
|---|---|
| Frequency content does not change over the record | Fourier transforms on the whole signal |
| You need fine time resolution at high frequencies and fine frequency resolution at low ones | Wavelets |
| You want a few summary numbers per frame, not a full picture | Signal feature extraction |
Math foundations
Short-time Fourier transform
The Fourier transform of the windowed frame that starts at sample . Row is a moment in time and column is frequency .
Spectrogram and its resolution
Power at each time and frequency. Bins are Hz apart and frames are seconds apart. Each frame lasts seconds, so sharper frequency resolution means blurrier timing.
The mel scale
A map from Hz to a scale on which equal steps sound about equally large, and its inverse. Band centres are placed at equal steps of and converted back to Hz.
Mel spectrogram
Each row of the filterbank is a triangle that rises from the previous band centre to its own and falls to the next. The sum pools the power of the bins under that triangle into one number.
MFCC
The orthonormal discrete cosine transform of the log mel energies, with and otherwise. It describes the shape of the spectrum with a few nearly uncorrelated numbers.
Welch power spectral density
The average of the frame spectra, scaled so that integrating over frequency gives the mean power of the signal. The factor 2 folds negative frequencies onto positive ones and is left out at 0 Hz and at the Nyquist bin. Averaging frames reduces the noise of the estimate.
Inverse by overlap-add
Each is the inverse FFT of frame , which equals the windowed original. Windowing again and dividing by the summed squared windows cancels the window wherever the denominator is not zero.
Symbols
- the signal at sample
- the analysis 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 sample rate in Hz
- the STFT, a complex number per frame and bin
- the power spectrogram
- a value in mels and a frequency in Hz
- the mel filterbank: weight of bin in band
- the number of mel bands (n_mels)
- the mel spectrogram
- the number of frames
- the inverse FFT of frame
Worked by hand
Use the default config on one second of audio: , , , with center on, so the signal is padded by 256 samples on each side.
The STFT is a 126 by 257 complex matrix. Each cell covers a 32 ms stretch of time and sits 31.25 Hz from its neighbours, and consecutive frames overlap by three quarters.
Visual example
Loading the example.
Try this
- With the sweep, go from 256 samples to 32: the click sharpens to a thin vertical line while the sweep turns into a thick band.
- Choose the two steady tones. They merge into one band until the frame is 128 samples or longer.
- Switch the window to rectangular and see power spill far above and below each tone.
Code sample
import numpy as np
from impl import Spectral
from config import SpectralConfig
sr = 16000
x = np.sin(2 * np.pi * 1000 * np.arange(sr) / sr) # one second of a 1 kHz tone
sp = Spectral(SpectralConfig(sample_rate=sr, n_fft=512, hop_length=128))
S = sp.stft(x) # complex (126, 257)
power = sp.spectrogram(x) # peaks in bin 32 = 1000 Hz
mel = sp.mel_spectrogram(x) # (126, 40)
coeffs = sp.mfcc(x) # (126, 13)
y = sp.istft(S, length=x.size) # equals x
freqs, psd = sp.welch_psd(x) # density peaks at 1000 HzRead the implementation (140 lines)
"""Spectral analysis: STFT, spectrogram, mel spectrogram, MFCC and Welch power spectral density.
The short-time Fourier transform cuts the signal into overlapping windowed frames and takes the FFT of each.
Everything else is built on it: the spectrogram is its squared magnitude, the mel spectrogram pools bins into
perceptually spaced bands, MFCCs are the cosine transform of the log mel energies, and Welch's method averages
frame spectra into a low-variance estimate of the power spectral density. `istft` inverts the STFT.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import SpectralConfig
except ImportError: # run from the template's own folder
from config import SpectralConfig
def hz_to_mel(freq) -> np.ndarray:
"""Frequency in Hz to mels, with the HTK formula 2595 log10(1 + f / 700)."""
return 2595.0 * np.log10(1.0 + np.asarray(freq, dtype=float) / 700.0)
def mel_to_hz(mel) -> np.ndarray:
"""Mels to frequency in Hz: the inverse of `hz_to_mel`."""
return 700.0 * (10.0 ** (np.asarray(mel, dtype=float) / 2595.0) - 1.0)
class Spectral:
"""Time-frequency analysis with fixed frame, hop and window."""
def __init__(self, config: SpectralConfig | None = None) -> None:
self.config = config or SpectralConfig()
n = self.config.n_fft
phase = 2.0 * np.pi * np.arange(n) / n # periodic form, right for overlapping frames
if self.config.window == "hann":
self.window = 0.5 - 0.5 * np.cos(phase)
elif self.config.window == "hamming":
self.window = 0.54 - 0.46 * np.cos(phase)
else:
self.window = np.ones(n)
def bin_frequencies(self) -> np.ndarray:
"""Centre frequency in Hz of each FFT bin, array (n_fft // 2 + 1,)."""
return np.arange(self.config.n_fft // 2 + 1) * self.config.sample_rate / self.config.n_fft
def frame_times(self, n_frames: int) -> np.ndarray:
"""Time in seconds of each frame: its centre when `center` is on, else its first sample."""
return np.arange(n_frames) * self.config.hop_length / self.config.sample_rate
def _frames(self, x: np.ndarray, center: bool) -> np.ndarray:
n, hop = self.config.n_fft, self.config.hop_length
if center:
x = np.pad(x, n // 2, mode="reflect" if x.size > n // 2 else "constant")
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 stft(self, x) -> np.ndarray:
"""Short-time Fourier transform of x, array (n,). Returns complex array (n_frames, n_fft // 2 + 1)."""
x = np.asarray(x, dtype=float).ravel()
return np.fft.rfft(self._frames(x, self.config.center) * self.window, axis=1)
def istft(self, spectrum, length: int | None = None) -> np.ndarray:
"""Invert `stft` by windowed overlap-add, normalized by the summed squared window.
spectrum: complex array (n_frames, n_fft // 2 + 1). length: number of samples to return.
Exact wherever frames overlap enough for the squared windows to sum to more than zero.
"""
spectrum = np.asarray(spectrum)
n, hop = self.config.n_fft, self.config.hop_length
frames = np.fft.irfft(spectrum, n, axis=1) * self.window
total = np.zeros((frames.shape[0] - 1) * hop + n)
weight = np.zeros_like(total)
for i, frame in enumerate(frames):
total[i * hop: i * hop + n] += frame
weight[i * hop: i * hop + n] += self.window**2
out = np.divide(total, weight, out=np.zeros_like(total), where=weight > 1e-10)
if self.config.center:
out = out[n // 2: out.size - n // 2]
return out if length is None else np.concatenate([out, np.zeros(max(length - out.size, 0))])[:length]
def spectrogram(self, x, power: float = 2.0) -> np.ndarray:
"""|STFT|^power, array (n_frames, n_fft // 2 + 1). power 2 is the power spectrogram, 1 the magnitude."""
return np.abs(self.stft(x)) ** power
def mel_filterbank(self) -> np.ndarray:
"""Triangular filters equally spaced on the mel scale. Returns array (n_mels, n_fft // 2 + 1).
Filter m rises from the centre of filter m - 1 to its own centre and falls to the centre of filter m + 1,
so neighbouring filters sum to 1 between the first and last centres.
"""
cfg = self.config
fmax = cfg.fmax if cfg.fmax is not None else cfg.sample_rate / 2.0
edges = mel_to_hz(np.linspace(hz_to_mel(cfg.fmin), hz_to_mel(fmax), cfg.n_mels + 2))
freqs = self.bin_frequencies()[None, :]
rising = (freqs - edges[:-2, None]) / (edges[1:-1, None] - edges[:-2, None])
falling = (edges[2:, None] - freqs) / (edges[2:, None] - edges[1:-1, None])
return np.maximum(0.0, np.minimum(rising, falling))
def mel_centers(self) -> np.ndarray:
"""Centre frequency in Hz of each mel band, array (n_mels,)."""
cfg = self.config
fmax = cfg.fmax if cfg.fmax is not None else cfg.sample_rate / 2.0
return mel_to_hz(np.linspace(hz_to_mel(cfg.fmin), hz_to_mel(fmax), cfg.n_mels + 2))[1:-1]
def mel_spectrogram(self, x) -> np.ndarray:
"""Power spectrogram pooled into mel bands. Returns array (n_frames, n_mels)."""
return self.spectrogram(x) @ self.mel_filterbank().T
def dct_matrix(self) -> np.ndarray:
"""Orthonormal DCT-II basis, array (n_mfcc, n_mels): row k is cos(pi k (m + 1/2) / n_mels), scaled."""
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 basis
def mfcc(self, x) -> np.ndarray:
"""Mel-frequency cepstral coefficients: DCT of the log mel energies. Returns array (n_frames, n_mfcc)."""
return np.log(self.mel_spectrogram(x) + 1e-10) @ self.dct_matrix().T
def welch_psd(self, x) -> tuple[np.ndarray, np.ndarray]:
"""Welch estimate of the one-sided power spectral density.
Averages the windowed periodograms of all frames (no centring). Returns (frequencies in Hz, density),
both arrays (n_fft // 2 + 1,). The density is in signal units squared per Hz: its integral over
frequency is the mean power of the signal.
"""
x = np.asarray(x, dtype=float).ravel()
n = self.config.n_fft
if x.size < n:
raise ValueError("the signal is shorter than one frame")
frames = self._frames(x, center=False) * self.window
density = np.mean(np.abs(np.fft.rfft(frames, axis=1)) ** 2, axis=0)
density /= self.config.sample_rate * np.sum(self.window**2)
last = n // 2 if n % 2 == 0 else n // 2 + 1
density[1:last] *= 2.0 # fold the negative frequencies onto the positive ones
return self.bin_frequencies(), density- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Build a one-second signal at 16 kHz that is a 440 Hz sine for the first half and an 880 Hz sine for the second. With Spectral(), check the shape of stft(x), find the strongest bin of spectrogram(x) in an early and a late frame, and confirm that istft(stft(x), len(x)) matches x. Then compare welch_psd for white noise with its expected flat level.
Check on learning
- You need to locate a click to within 2 ms and also separate two tones that are 10 Hz apart. Can one STFT setting do both at 16 kHz? Why not?
A way to think about it
Compute the frame length that gives 10 Hz bins, then ask how precisely an event can be placed inside a frame that long.
- Why does the inverse divide by the sum of squared windows, not by the sum of the windows?
A way to think about it
Count how many times the window multiplies each sample on the way from the signal back to the signal: once in the analysis and once more in the synthesis.
- A single frame's spectrum of white noise is very ragged, while Welch's estimate is smooth. What is being traded for that smoothness?
A way to think about it
Averaging more frames needs either a longer recording or shorter frames. Think about what shorter frames do to .
- Mel bands get wider as frequency rises. For which kind of signal would this throw away information you need?
A way to think about it
Consider a machine whose fault shows up as two narrow tones near 6 kHz. Check how wide a mel band is up there.
- With center off, how many frames does a one-second signal give under the default config, and which samples are covered less well than the rest?
A way to think about it
Apply the frame-count formula without the padding. Then look at how many windows overlap the first few samples compared with the middle.