6. Spectrograms & the STFT

Seeing sound — frequency over time

The DFT is a powerful lens — it takes a chunk of signal and tells you exactly which frequencies are present and how strong they are. But it has a blind spot: it collapses time entirely. Run a DFT over a five-second recording of a piano, and you'll see which notes were played. You won't know whether the A4 came before or after the C5, or whether they were struck together. The DFT answers what, not when.

Music has notes that start and stop. Speech weaves vowels and consonants together in rapid succession. A seismic tremor builds and dissipates. For these signals, we need both time and frequency at once. That's what the spectrogram gives us.

The Time-Frequency Trade-off

Before we get to the machinery, there's a fundamental limit worth understanding. It's analogous to Heisenberg's uncertainty principle in quantum mechanics, and it's just as inescapable.

Suppose you want to know the pitch of a single note at a precise instant. To measure frequency accurately, you need to observe several cycles of the wave — you can't determine the frequency of a sinusoid from a single sample. But the more cycles you observe, the more time elapses, and the less precisely you can say when the note occurred.

You cannot have perfect resolution in both time and frequency simultaneously. Narrowing one necessarily blurs the other. This is not a limitation of our instruments — it is a mathematical consequence of the Fourier transform itself.

Concretely: if your analysis window is T seconds long, the finest frequency detail you can resolve is roughly 1/T Hz. A one-second window resolves frequencies to within 1 Hz — good for pitch. A 10-millisecond window resolves to within 100 Hz — enough to track fast articulation, but hopeless for distinguishing closely spaced harmonics.

Every spectrogram is a negotiation between these two demands.

The Short-Time Fourier Transform (STFT)

The solution is straightforward: don't run one DFT over the whole signal. Instead, slide a short analysis window across it, compute the DFT of each windowed segment, and stack the results side by side. This is the Short-Time Fourier Transform (STFT).

Diagram

The Short-Time Fourier Transform

Time-domain signal Window 1 Window 2 Window 3 Spectrum 1 Spectrum 2 Spectrum 3 Slide window, compute DFT at each position
The STFT slides an analysis window across the signal. Each window position yields one DFT spectrum. The frequency content changes from window to window, capturing how the signal evolves.

Formally, the STFT at time τ and frequency f is:

STFT(τ, f) = ∫ x(t) · w(t − τ) · e−j2πft dt

where w(t) is the window function — typically a Hann or Hamming window, which tapers the edges of each segment to reduce spectral leakage (the same concern we examined in the windowing article). The result is a complex number for each (τ, f) pair: its magnitude tells you how strongly that frequency was present at that time, its phase tells you the waveform's alignment.

Reading a Spectrogram

A spectrogram is just the magnitude of the STFT plotted as an image. Time runs left to right on the horizontal axis, frequency increases from bottom to top on the vertical axis, and color (or brightness) encodes the magnitude — typically in decibels, since our perception of loudness is logarithmic.

Diagram

Anatomy of a spectrogram

0 Hz 4 kHz 8 kHz Frequency 0 s 1 s 2 s Time Fundamental Harmonics Formant region Low High Magnitude (dB)
Anatomy of a spectrogram. Time flows left to right, frequency increases upward, and color encodes magnitude in decibels. Bright horizontal bands are sustained harmonics. Short bright patches are transient events. Formant regions — peaks in the spectral envelope — shift with vowel sounds.

A few landmarks to learn to read:

  • Horizontal stripes — sustained tones at fixed frequencies. A held note on a piano creates several parallel stripes (the fundamental and its harmonics).
  • Vertical smears — broadband transients. A clap, a drum hit, or a consonant like "t" produces a momentary splash of energy across many frequencies.
  • Frequency glides — a diagonal streak means the pitch is rising or falling. A siren, a slide guitar, a whistled melody.
  • Formants — in speech, the resonant frequencies of the vocal tract concentrate energy into bands called formants. Different vowels have distinct formant patterns that are clearly visible in a spectrogram.

Window Size and the Resolution Trade-off

The window length is the central design choice. There's no universally right answer — only trade-offs, depending on what you're trying to see.

Diagram

Window size and resolution

Short window Good time resolution — onsets are sharp Poor frequency resolution — bands blurred Long window Poor time resolution — onsets smear out Good frequency resolution — bands crisp Time → Time → The trade-off, concretely: Short window (e.g. 5 ms): resolves to ~200 Hz — tracks rapid articulation, misses pitch detail Long window (e.g. 100 ms): resolves to ~10 Hz — reveals pitch and harmonics, blurs onset timing
The window length governs the fundamental trade-off. Short windows capture when events happen; long windows reveal what pitches are present. The right choice depends on which matters more for your application.

In speech processing, a common compromise is a 25 ms window — short enough to capture the rapid changes of consonants, long enough to resolve the harmonics of voiced speech. In music analysis you might use longer windows when tracking pitch and shorter ones when detecting onsets.

Overlap

Consecutive windows in an STFT nearly always overlap. Typical overlap is 50% to 75% of the window length. There are two reasons for this:

Smoother temporal coverage. A non-overlapping analysis would "miss" information that falls near the edges of each window, where the taper reduces the weight of the signal. Overlapping windows ensure every sample is well-represented in at least one window where it's near the center.

Finer time steps in the output. With 75% overlap and a 20 ms window, you produce a new spectrum every 5 ms, giving you 200 time frames per second even though each frame spans 20 ms. The result is a smoother, more readable spectrogram.

The cost is computation — overlapping windows mean more DFTs to compute. But since each DFT is small (just one window length), this is tractable, especially with FFT acceleration.

Applications

Spectrograms appear wherever signals change over time and you need to see how their frequency content evolves.

Speech processing. A spectrogram of a spoken sentence makes the phonetic structure visible. Vowels show clear formant tracks — upward and downward sweeping arcs as the vocal tract changes shape. Fricatives (/s/, /sh/) produce broadband high-frequency hiss. Stops (/p/, /t/, /k/) show as brief silences followed by bursts. Voice identification systems analyze spectral patterns that are unique to each speaker's vocal tract geometry.

Music analysis. Pitch detection algorithms track the fundamental frequency of a melody by following the lowest harmonic. Chord detection looks for co-occurring harmonic series. Music information retrieval systems use spectrogram features (mel-frequency cepstral coefficients, derived from a perceptually-scaled spectrogram) for genre classification, cover-song detection, and audio fingerprinting.

Seismology. Earthquake signals span a wide range of frequencies. P-waves arrive first and carry higher-frequency energy; slower S-waves carry lower frequencies. A spectrogram of a seismogram lets analysts distinguish wave types, estimate source distances, and identify explosion signatures (which look different from tectonic events).

Radio spectrum monitoring. A real-time spectrogram of a radio band shows every transmission as it begins and ends — a band occupied by a frequency-hopping spread-spectrum signal looks like a flickering, rapidly moving streak. Spectrum analyzers are essentially specialized spectrogram displays.

Bioacoustics. Birdsong species identification from recordings is nearly automatic now — each species has a characteristic spectral signature: the hermit thrush's long ascending spirals, the wood thrush's flute-like phrases. Whale biologists use spectrograms to identify calls from blue, fin, and humpback whales in long hydrophone recordings, tracking migration patterns across ocean basins.

The Uncertainty Principle

The trade-off we've been discussing has a precise mathematical statement. If Δt is the temporal resolution (the effective duration of the analysis window) and Δf is the frequency resolution (the finest frequency detail resolvable), then:

Δt · Δf ≥ 1 / (4π)

This is the Gabor limit (or time-frequency uncertainty principle), named after Dennis Gabor, who introduced the concept of the STFT in 1946. The Gaussian window is the only window function that achieves the equality — it's the optimal compromise. Every other window sits above this bound.

Worked example: A Hann window of length 1024 samples at 44.1 kHz sampling rate.

  • Window duration: T = 1024 / 44100 ≈ 23 ms
  • Frequency resolution: Δf ≈ 1/T ≈ 43 Hz
  • Time resolution: Δt ≈ T/2 ≈ 12 ms (effective, due to the taper)
  • Product: 12 ms × 43 Hz ≈ 0.52, well above 1/(4π) ≈ 0.08

To resolve pitches 10 Hz apart, you'd need T ≥ 100 ms — which smears all onsets across a tenth of a second. You cannot have both.

This is not a bug in the STFT — it is a property of Fourier analysis itself. Any time-frequency representation you can construct is subject to the same bound.

Beyond the STFT: Wavelets

The STFT uses a fixed window size everywhere in the signal. But some signals demand different trade-offs at different frequencies. A bass drum thump sits at 50–100 Hz and you need good frequency resolution there; a hi-hat click sits at 8–12 kHz and you need good time resolution there. Using the same window for both is a compromise.

Wavelets solve this by using windows that scale with frequency: short windows for high frequencies (good time resolution where the signal changes fast) and long windows for low frequencies (good frequency resolution where pitch precision matters). The continuous wavelet transform and its discrete variants are the result — a richer representation at the cost of greater conceptual and computational complexity.

Wavelets are used extensively in image compression (JPEG 2000 uses a wavelet transform rather than a DCT), denoising, and biomedical signal analysis. But for audio work, the STFT remains the workhorse: simpler, faster, and good enough for most purposes.

Key Takeaways

  • The DFT tells you which frequencies are present in a signal, but not when. For time-varying signals, you need the STFT.
  • The STFT slides an analysis window across the signal and computes a DFT at each position, producing a time-frequency map.
  • A spectrogram is the magnitude of the STFT: time on the x-axis, frequency on the y-axis, magnitude as color.
  • Time and frequency resolution are fundamentally at odds. A short window gives sharp timing but blurry pitch; a long window gives sharp pitch but blurry timing. You cannot improve both simultaneously.
  • The Gabor limit Δt · Δf ≥ 1/(4π) is a hard mathematical bound, not an engineering limitation.
  • Overlap (50–75%) between windows ensures smooth coverage and fine temporal sampling in the output.
  • Wavelets generalize the STFT by adapting the window length to frequency — short windows at high frequencies, long windows at low.

Try It — Spectrogram Visualizer

The signal below contains a frequency chirp sweeping from 50 Hz to 350 Hz, a sustained 150 Hz tone, and two short broadband clicks. Drag the window size slider to see the time-frequency trade-off in action: small windows sharpen the clicks but blur the chirp; large windows resolve the frequencies but smear the timing.

128
75%