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 of length and hop size :
Row is a frequency ( Hz), column a time ( seconds). The spectrogram is , usually in decibels.
A chirp and a tone change
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 gives frequency resolution and time resolution about . Their product is fixed.
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 olderstft/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 , produce from 2 s of audio at 16 kHz?
Answer
124 frames, 257 bins.
Solution
samples, frames (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
plus the same shifted by is , 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
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…
- amplitude against time only
- the magnitude of the STFT as a function of time and frequency
- the phase of one FFT
- the impulse response
Making STFT frames longer…
- improves time resolution
- improves frequency resolution but worsens time resolution
- improves both
- changes nothing
With Hz and , the bin spacing is…
- 8 Hz
- 31.25 Hz
- 256 Hz
- 4000 Hz