Sign in

Spectral

Spectral analysis with the short-time Fourier transform (STFT)

Shows how a signal's frequency content changes over time, through the short-time Fourier transform and the spectrogram, mel and MFCC views built on it.

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

  1. Choose a frame length n_fft and a hop_length. With center on, the signal is padded by reflection so that frame tt is centred on sample tt times the hop.
  2. Multiply each frame by a window (Hann by default) so its ends fade to zero.
  3. 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.
  4. Square the magnitudes to get the power spectrogram.
  5. Multiply by a bank of triangular filters spaced evenly on the mel scale to get the mel spectrogram.
  6. Take the log and apply a discrete cosine transform to get MFCCs, keeping the first n_mfcc coefficients.
  7. 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

IfUse instead
Frequency content does not change over the recordFourier transforms on the whole signal
You need fine time resolution at high frequencies and fine frequency resolution at low onesWavelets
You want a few summary numbers per frame, not a full pictureSignal feature extraction

Math foundations

  1. Short-time Fourier transform

    X[t,k]=∑n=0N−1w[n] x[tH+n] e−2πikn/NX[t, k] = \sum_{n=0}^{N-1} w[n]\,x[tH + n]\,e^{-2\pi i k n / N}

    The Fourier transform of the windowed frame that starts at sample tHtH. Row tt is a moment in time and column kk is frequency kfs/Nk f_s / N.

  2. Spectrogram and its resolution

    S[t,k]=∣X[t,k]∣2,Δf=fsN,Δt=HfsS[t, k] = \big|X[t, k]\big|^{2}, \qquad \Delta f = \frac{f_s}{N}, \qquad \Delta t = \frac{H}{f_s}

    Power at each time and frequency. Bins are fs/Nf_s / N Hz apart and frames are H/fsH / f_s seconds apart. Each frame lasts N/fsN / f_s seconds, so sharper frequency resolution means blurrier timing.

  3. The mel scale

    m(f)=2595 log⁡10 ⁣(1+f700),f(m)=700(10 m/2595−1)m(f) = 2595\,\log_{10}\!\left(1 + \frac{f}{700}\right), \qquad f(m) = 700\left(10^{\,m / 2595} - 1\right)

    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 mm and converted back to Hz.

  4. Mel spectrogram

    M[t,b]=∑kB[b,k] S[t,k]M[t, b] = \sum_{k} B[b, k]\,S[t, k]

    Each row of the filterbank BB 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.

  5. MFCC

    c[t,j]=aj∑b=0Bm−1log⁡M[t,b] cos⁡ ⁣(πj (b+12)Bm)c[t, j] = a_j \sum_{b=0}^{B_m - 1} \log M[t, b]\,\cos\!\left(\frac{\pi j\,(b + \tfrac{1}{2})}{B_m}\right)

    The orthonormal discrete cosine transform of the log mel energies, with a0=1/Bma_0 = \sqrt{1/B_m} and aj=2/Bma_j = \sqrt{2/B_m} otherwise. It describes the shape of the spectrum with a few nearly uncorrelated numbers.

  6. Welch power spectral density

    P^[k]=2fs∑nw[n]2⋅1T∑t=0T−1∣X[t,k]∣2\hat{P}[k] = \frac{2}{f_s \sum_{n} w[n]^{2}} \cdot \frac{1}{T}\sum_{t=0}^{T-1} \big|X[t, k]\big|^{2}

    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 TT frames reduces the noise of the estimate.

  7. Inverse by overlap-add

    x^[n]=∑tw[n−tH] yt[n−tH]∑tw[n−tH]2\hat{x}[n] = \frac{\sum_{t} w[n - tH]\,y_t[n - tH]}{\sum_{t} w[n - tH]^{2}}

    Each yty_t is the inverse FFT of frame tt, which equals the windowed original. Windowing again and dividing by the summed squared windows cancels the window wherever the denominator is not zero.

Symbols

x[n]x[n]
the signal at sample nn
w[n]w[n]
the analysis window
NN
the frame length and FFT size (n_fft)
HH
the hop between frames in samples (hop_length)
t, kt,\ k
the frame index and the frequency bin index
fsf_s
the sample rate in Hz
X[t,k]X[t, k]
the STFT, a complex number per frame and bin
S[t,k]S[t, k]
the power spectrogram
m, fm,\ f
a value in mels and a frequency in Hz
B[b,k]B[b, k]
the mel filterbank: weight of bin kk in band bb
BmB_m
the number of mel bands (n_mels)
M[t,b]M[t, b]
the mel spectrogram
TT
the number of frames
yty_t
the inverse FFT of frame tt

Worked by hand

Use the default config on one second of audio: fs=16000f_s = 16000, N=512N = 512, H=128H = 128, with center on, so the signal is padded by 256 samples on each side.

Δf=16000512=31.25 Hz,bins=5122+1=257\Delta f = \frac{16000}{512} = 31.25 \ \text{Hz}, \qquad \text{bins} = \frac{512}{2} + 1 = 257
frame length=51216000=32 ms,Δt=12816000=8 ms\text{frame length} = \frac{512}{16000} = 32 \ \text{ms}, \qquad \Delta t = \frac{128}{16000} = 8 \ \text{ms}
frames=1+⌊16000+2×256−512128⌋=1+125=126\text{frames} = 1 + \left\lfloor \frac{16000 + 2 \times 256 - 512}{128} \right\rfloor = 1 + 125 = 126

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 Hz
Read 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

  1. 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.

  2. 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.

  3. 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 Δf\Delta f.

  4. 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.

  5. 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.