TExcelTAD
Home › Fourier Analysis & Signals › The Short-Time Fourier Transform

The Short-Time Fourier Transform

A single FFT of a whole song tells you which frequencies occur, but not when. The short-time Fourier transform (STFT) slides a window along the signal and takes an FFT of each frame; the result, shown as an image of time against frequency, is the spectrogram. It is the standard view of speech, music, bird song and radar returns, and the input to most audio machine-learning models.

Definition

With window ww of length LL and hop size HH:

X[m,k]=∑n=0L−1x[n+mH] w[n] e−2πikn/LX[m, k] = \sum_{n=0}^{L-1} x[n + mH]\, w[n]\, e^{-2\pi i k n / L}

Row kk is a frequency (kfs/Lk f_s / L Hz), column mm a time (mH/fsm H / f_s seconds). The spectrogram is ∣X[m,k]∣2\lvert X[m, k] \rvert^2, usually in decibels.

A chirp and a tone change

python · try it yourself
import numpy as np

fs = 8000
t = np.arange(0, 1.0, 1 / fs)
x = np.where(t < 0.5, np.sin(2 * np.pi * 440 * t), np.sin(2 * np.pi * 880 * t))   # a step up an octave

def stft(x, L=256, H=128):
    w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(L) / L)
    frames = [x[i:i + L] * w for i in range(0, len(x) - L + 1, H)]
    return np.abs(np.fft.rfft(frames, axis=1))

S = stft(x)
freqs = np.fft.rfftfreq(256, 1 / fs)
peak = freqs[np.argmax(S, axis=1)]
times = np.arange(S.shape[0]) * 128 / fs
for m in range(0, S.shape[0], 6):
    print(f"t = {times[m]:.3f} s: strongest frequency {peak[m]:6.1f} Hz")
t = 0.000 s: strongest frequency  437.5 Hz
t = 0.096 s: strongest frequency  437.5 Hz
t = 0.192 s: strongest frequency  437.5 Hz
t = 0.288 s: strongest frequency  437.5 Hz
t = 0.384 s: strongest frequency  437.5 Hz
t = 0.480 s: strongest frequency  437.5 Hz
t = 0.576 s: strongest frequency  875.0 Hz
t = 0.672 s: strongest frequency  875.0 Hz
t = 0.768 s: strongest frequency  875.0 Hz
t = 0.864 s: strongest frequency  875.0 Hz
t = 0.960 s: strongest frequency  875.0 Hz

With 256-sample frames the bins are 31.25 Hz apart, so 440 Hz is reported as the nearest bin, 437.5 Hz, and 880 Hz exactly. Finer frequency would need longer frames.

Time versus frequency resolution

The uncertainty principle appears directly: frame length LL gives frequency resolution fs/Lf_s/L and time resolution about L/fsL/f_s. Their product is fixed.

python · try it yourself
import numpy as np

fs = 8000
for L in (64, 256, 1024, 4096):
    print(f"frame {L:5d} samples: {1000 * L / fs:7.1f} ms per frame, {fs / L:7.2f} Hz per bin")

t = np.arange(0, 1.0, 1 / fs)
chirp = np.sin(2 * np.pi * (200 * t + 1500 * t ** 2))        # frequency rises 200 -> 3200 Hz
for L in (128, 2048):
    w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(L) / L)
    mid = fs // 2 - L // 2                                   # frame centered at t = 0.5 s
    A = np.abs(np.fft.rfft(chirp[mid:mid + L] * w))
    width = np.sum(A > A.max() / 2) * fs / L
    print(f"chirp at t = 0.5 s (true 1700 Hz), frame {L}: peak {np.fft.rfftfreq(L, 1 / fs)[np.argmax(A)]:.0f} Hz, -6 dB width {width:.0f} Hz")
frame    64 samples:     8.0 ms per frame,  125.00 Hz per bin
frame   256 samples:    32.0 ms per frame,   31.25 Hz per bin
frame  1024 samples:   128.0 ms per frame,    7.81 Hz per bin
frame  4096 samples:   512.0 ms per frame,    1.95 Hz per bin
chirp at t = 0.5 s (true 1700 Hz), frame 128: peak 1688 Hz, -6 dB width 125 Hz
chirp at t = 0.5 s (true 1700 Hz), frame 2048: peak 1699 Hz, -6 dB width 383 Hz

The short frame resolves the moment well but blurs frequency; the long frame sees the chirp sweep through about 750 Hz during the frame and smears it.

Inverting the STFT

With a suitable window and hop (for example Hann with 50 % overlap, which sums to a constant), overlap-adding the inverse FFTs of the frames reconstructs the signal exactly. That is how audio effects (noise reduction, time stretching, source separation) modify sound in the spectrogram domain.

In software

  • scipy.signal.ShortTimeFFT (or the older stft/istft/spectrogram), librosa.stft, torch.stft. Mel spectrograms (frequency axis warped to match hearing) are the standard input of speech recognizers.
  • Typical speech settings: 25 ms frames with a 10 ms hop at 16 kHz.

Exercises

Exercise 1: Grid size

How many frames and frequency bins does an STFT with L=512L = 512, H=256H = 256 produce from 2 s of audio at 16 kHz?

Answer

124 frames, 257 bins.

Solution

N=32000N = 32000 samples, frames ⌊(32000−512)/256⌋+1=124\lfloor (32000 - 512)/256 \rfloor + 1 = 124 (without padding), and rfft of 512 samples gives 257 bins.

Exercise 2: Constant overlap-add

Why does a Hann window with 50 % overlap allow perfect reconstruction by simple addition?

Answer

Shifted copies of the periodic Hann window by half its length add up to exactly 1.

Solution

0.5−0.5cos⁡(2πn/L)0.5 - 0.5\cos(2\pi n/L) plus the same shifted by L/2L/2 is 0.5−0.5cos⁡(⋅)+0.5+0.5cos⁡(⋅)=10.5 - 0.5\cos(\cdot) + 0.5 + 0.5\cos(\cdot) = 1, so the windows' weights cancel when the frames are added back together.

Exercise 3: Check the overlap-add sum (code)

Verify numerically that periodic Hann windows of length 256 with hop 128 sum to 1 away from the edges.

Answer

The sum is 1 everywhere in the interior.

Solution
python · try it yourself
import numpy as np
L, H = 256, 128
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(L) / L)
total = np.zeros(L * 10)
for start in range(0, len(total) - L + 1, H):
    total[start:start + L] += w
print(np.allclose(total[L:-L], 1.0), round(float(total[L:-L].min()), 12), round(float(total[L:-L].max()), 12))
True 1.0 1.0

Test yourself

A spectrogram shows…

  1. amplitude against time only
  2. the magnitude of the STFT as a function of time and frequency
  3. the phase of one FFT
  4. the impulse response

Making STFT frames longer…

  1. improves time resolution
  2. improves frequency resolution but worsens time resolution
  3. improves both
  4. changes nothing

With fs=8000f_s = 8000 Hz and L=256L = 256, the bin spacing is…

  1. 8 Hz
  2. 31.25 Hz
  3. 256 Hz
  4. 4000 Hz