CodeRigor

LESSON

Windows and spectrograms

Cut a signal into Hann-windowed frames, build a spectrogram, invert it by overlap-add, and measure what the window does to leakage and onsets.

A Fourier transform describes a whole signal at once, but sound changes: a note starts, a drum hits, a word ends. The short-time Fourier transform cuts the signal into overlapping frames, transforms each one, and stacks the results into a picture of frequency against time. The cut has a side effect, because a frame is a slice taken with scissors, and the window you fade it with decides how badly that slice smears the spectrum. This lesson pairs with Coding Adventure: Analyzing Audio by Sebastian Lague, linked under Watch & read. The video covers the short-time transform, time and frequency resolution, the Hann window, hop and segment size, and turning a spectrogram back into sound. You build hann, frames, stft, istft, spectrogram_db, leakage and onsets in NumPy and check them against independent oracles.

Take a signal x, a frame size and a hop. Frame t holds the samples from t · hop to t · hop + size - 1. If the hop is smaller than the size, neighbouring frames overlap. In this lesson a frame that would run past the end of x is dropped, so a signal of length L gives 1 + (L - size) // hop frames, and none when L is shorter than one frame. Each frame is multiplied by a window and sent through a real FFT, so row t of the result has size // 2 + 1 bins.

From samples to a spectrogram
start / 5
Each frame is faded by the window, transformed, and becomes one column of the picture. Time runs along the frames, frequency along the bins.
From samples to a spectrogram
Each frame is faded by the window, transformed, and becomes one column of the picture. Time runs along the frames, frequency along the bins.

The transform treats a frame as one period of a signal that repeats forever. If the frame does not end where it began, the jump from the last sample back to the first looks like a click, and a click contains every frequency. The Hann window, 0.5 - 0.5 cos(2πk / n), fades both ends to zero so the jump disappears. Use the periodic form, with n in the denominator: it is NumPy's hanning(n + 1) with the last point dropped, because one period of a repeating window must not contain its own first point twice. NumPy's hanning(n) is the symmetric form, which is right for filter design and slightly wrong here.

Python
import numpy as np

n = 8
periodic = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)
print(periodic.round(4).tolist())
print(np.allclose(periodic, np.hanning(n + 1)[:-1]), np.hanning(n).round(4).tolist()[:3])

The size sets both resolutions. Bins are rate / size hertz apart and a frame lasts size / rate seconds. At 8000 samples per second, 64 points give 125 Hz bins and 8 ms frames, while 256 points give 31.25 Hz bins and 32 ms frames. You cannot have both fine pitch and fine timing from one size. The hop only sets how often you look; it does not add information.

Leakage is the energy that lands away from the tone's own frequency. A cosine that fits a whole number of cycles in the frame puts everything on one bin. A cosine halfway between two bins does not, and with no window the energy trails off slowly. The leakage function reports the share of energy two or more bins from the tone, which separates the main lobe from the side lobes.

Python
import numpy as np

n = 64
t = np.arange(n)
for freq in (8.0, 8.5):
    tone = np.cos(2 * np.pi * freq * t / n)
    for name, w in (("rect", np.ones(n)), ("hann", 0.5 - 0.5 * np.cos(2 * np.pi * t / n))):
        e = np.abs(np.fft.rfft(tone * w)) ** 2
        far = np.abs(np.arange(len(e)) - freq) >= 2
        print(freq, name, round(e[far].sum() / e.sum(), 4))

The price of the Hann window is a wider main lobe: its main lobe is four bins wide where the rectangular one is two, so two close tones are harder to tell apart. The chart below plots the same off-bin tone both ways, in decibels relative to its own peak.

A tone between two bins, with and without the window
64-point frames, tone at bin 8.5. Each curve is in decibels below its own peak. The rectangular curve falls slowly; the Hann curve is 22 dB lower at bin 12 and 36 dB lower at bin 16.
A tone between two bins, with and without the window
64-point frames, tone at bin 8.5. Each curve is in decibels below its own peak. The rectangular curve falls slowly; the Hann curve is 22 dB lower at bin 12 and 36 dB lower at bin 16.

To go back from S to sound, take an inverse FFT of every row and add the rows into place. Each sample was multiplied by the window once on the way in; the inverse multiplies by it again, so the overlapped sum is x scaled by the sum of the squared windows. Divide that sum out and x returns. Only samples some window reaches can come back, and a Hann window is zero at its first point, so sample 0 has nothing to recover and is returned as 0.

Python
import numpy as np

size = 16
w2 = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(size) / size)) ** 2
for hop in (4, 8):
    total = np.zeros(64)
    for start in range(0, 64 - size + 1, hop):
        total[start:start + size] += w2
    print(hop, total[16:48].min().round(4), total[16:48].max().round(4))

With a hop of a quarter of the size the squared windows sum to a constant 1.5, so a missing division would only scale the sound. With a hop of half the size the sum wobbles between 0.5 and 1, and the output is modulated. Dividing by the actual sum at every sample works for any hop.

Two more tools use S. spectrogram_db is 20 log10 of the magnitude, with a floor so silence does not become minus infinity. onsets sums, for each frame, how much every bin's magnitude grew since the previous frame, and reports the first frame of each run above a threshold. It reports the start of the frame, which can be earlier than the sound itself: a frame that holds only its last few samples of a new tone already shows it.

Three mistakes are common. Taking NumPy's symmetric window leaves a tone on a bin centre with side lobes it should not have. Skipping the window-square division returns a scaled or rippled signal. Reading a frame's index as the time of its centre moves every onset by half a frame.

The tests compare your window with NumPy's, your transform with a direct DFT, each frame's energy with Parseval's relation, and the round trip on every covered sample for several hops. They do not show that a threshold suits a real recording, or that a spectrogram looks right to a person. Both depend on the signal.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Covers the short-time Fourier transform, the trade between time and frequency resolution, the Hann window, hop and segment size, and turning a spectrogram back into sound. Watch it first, then build the same pieces here.