---
title: The short-time Fourier transform
heading: Spectra that change with time, and the trade between seeing when and seeing which frequency
eyebrow: C9 · Lesson 26 · The short-time Fourier transform
xp: 40
---

::: hook
A DFT of a whole recording (lesson 24) says which frequencies occur but not when: a bird's rising chirp and a falling one have the same spectrum. Speech, music, radar returns and machine vibration all change from moment to moment, so engineers cut the signal into short windowed pieces (lesson 25), take a DFT of each, and stack the results into a **spectrogram**: time across, frequency up, brightness for magnitude. Choosing the piece length is the whole art. Short windows locate events sharply in time and blur frequency; long windows do the opposite, the duration-bandwidth limit of lesson 17 in a new form.
:::

::: play
- For a window of $L$ samples at sample rate $f_s$ = 8 kHz, the solid curve is the frequency resolution (Hann main-lobe half-width, $2f_s/L$) and the dashed curve the time resolution, $L/f_s$, both against window length.
- They move in opposite directions; their product is fixed at 2.
- A chirp sweeping at $\beta$ Hz per second smears across $\beta T$ hertz during a window of length $T$, so for a chirp there's a best window: where the smear equals the window's own resolution.
:::

```sim plot
view: graph
x: L = 32..4096 log
y: r = 0.001..1000 log
slider: b = 100..100000 = 1000 log
plot: 2*8000/L | label: frequency resolution, Hz
plot: L/8000*1000 | dashed | color: ch2 | label: time resolution, ms
readout: chirp-optimal window in ms = 1000/sqrt(b)
readout: bin spacing at L in Hz = 8000/1024
```

::: predict
## Speech sampled at 8 kHz is analyzed with 256-sample windows hopped by 128 samples. How many spectrogram frames does one second give?

- [ ] 31
- [ ] 32
- [x] 61
- [ ] 64

::: reveal
Frames start every 128 samples and need 256 samples each, so in 8000 samples there are $\lfloor(8000 - 256)/128\rfloor + 1$ = 61. Each frame covers 32 ms with bins 31.25 Hz apart, a common choice for speech: short enough to follow syllables, long enough to resolve the harmonics of a voice.
:::
:::

::: nameit
## The short-time Fourier transform

Multiply the signal by a window $w$ of length $L$ placed at hop $m$, and take the DFT:

$$X[m, k] = \sum_{n=0}^{L-1} x[n + mH]\,w[n]\,e^{-j2\pi kn/L}$$

with hop $H$. Frame $m$ describes the signal around time $mH/f_s$; bin $k$ is frequency $kf_s/L$.

## Resolution

- **Time:** an event is located to within about the window's length, $L/f_s$.
- **Frequency:** bins are $f_s/L$ apart, and a window's main lobe spreads a pure tone over several bins: a Hann window's main lobe reaches $\pm 2f_s/L$. Two tones are cleanly separated when they're about that far apart.

Their product is constant: halving the window doubles the frequency blur. Zero-padding each frame makes the plot smoother but doesn't change the resolution.

## Hop and overlap

Windows usually overlap by 50 to 75%, so nothing between frames is missed and the display is smooth. The number of frames from $N$ samples is $\lfloor(N - L)/H\rfloor + 1$. With a Hann window at 50% overlap, the shifted windows add up to a constant, so the frames can be modified and added back together to rebuild the signal: the basis of overlap-add processing.

## The best window for a chirp

A tone whose frequency rises at $\beta$ Hz/s moves by $\beta T$ during a window of length $T$, while the window's own resolution is about $1/T$. The total blur is smallest when the two are equal, at $T \approx 1/\sqrt\beta$.
:::

::: example
## Design a spectrogram for 8 kHz speech with 32 ms frames and 50% overlap. Give $L$, $H$, the bin spacing, the Hann main-lobe half-width, and the frames per second.

::: solution
1. **Frame and hop.**
   $$\begin{aligned} L &= 0.032 \times 8000 \\ &= 256\ \text{samples} \\ H &= 128 \end{aligned}$$
2. **Bins and main lobe.** The bins are
   $$8000/256 = 31.25\ \text{Hz}$$
   apart, and a Hann window spreads each tone over ±62.5 Hz.
3. **Frames per second.** One second gives
   $$\lfloor(8000 - 256)/128\rfloor + 1 = 61$$
   frames, a new frame every 16 ms.
4. **What it resolves.** A voice's harmonics, 100 to 250 Hz apart, are resolved; a 10 ms plosive is located to within one frame.

**Answer:** L = 256 and H = 128, bins 31.25 Hz apart, a Hann main-lobe half-width of 62.5 Hz, and 61 frames a second.
:::
:::

::: example
## A vibration signal sampled at 8 kHz contains two tones 20 Hz apart. How long a Hann window is needed to separate them, and what time resolution does that leave?

::: solution
1. **Window length.** The main-lobe half-width $2f_s/L$ must be at most 20 Hz, so
   $$\begin{aligned} L &\ge 2 \times 8000/20 \\ &= 800\ \text{samples} \end{aligned}$$
   which is 100 ms.
2. **Time resolution.** Events shorter than a tenth of a second will be smeared.
3. **When both matter.** If both separations matter, one display can't show them; analysts make two spectrograms, or use a wavelet transform whose window shrinks at high frequencies.

**Answer:** at least 800 samples (100 ms), which smears events shorter than a tenth of a second.
:::
:::

::: example
## A bat's chirp sweeps 1000 Hz per millisecond, $10^6$ Hz/s. What window length shows it most sharply?

::: solution
1. **Best window length.**
   $$\begin{aligned} T &\approx 1/\sqrt\beta \\ &= 1/\sqrt{10^6}\ \text{s} \\ &= 1\ \text{ms} \end{aligned}$$
2. **Why it balances.** During 1 ms the chirp moves 1 kHz, and a 1 ms window's own resolution is about 1 kHz: the two blurs balance.
3. **Longer or shorter.** A 10 ms window would smear the sweep over 10 kHz; a 0.1 ms window would blur each moment's frequency over 10 kHz. Either way it's ten times worse.

**Answer:** a window about 1 ms long.
:::
:::

::: check
given: fs = 8 | 16 | 44.1 | 48; L = 256 | 512 | 1024 | 4096
answer: fs*1e3/L
unit: Hz
tolerance: 0.5%

## A spectrogram of a {fs} kHz signal uses {L}-sample frames. How far apart are its frequency bins?

::: right
Right. $f_s/L$ = {answer}.
:::

::: misses
- [L/(fs*1e3)] That's the frame duration in seconds. Bins are $f_s/L$ apart.
- [fs*1e3/(2*L)] The bins span 0 to $f_s$ in $L$ steps.
- [any] Not yet. $\Delta f = f_s/L$.
:::
:::

::: check
given: N = 8000 | 16000 | 44100; L = 256 | 512 | 1024; o = 2 | 4
answer: floor((N - L)/(L/o)) + 1
tolerance: 0.1%

## A record of {N} samples is analyzed with {L}-sample frames hopped by {L}/{o}. How many complete frames fit?

::: right
Right. $\lfloor(N - L)/H\rfloor + 1$ = {answer}.
:::

::: misses
- [floor(N/(L/o))] The last frame must fit entirely in the record.
- [floor(N/L)] Frames overlap: they start every $L/\given{o}$ samples.
- [any] Not yet. $\lfloor(N - L)/H\rfloor + 1$ with $H = L/\given{o}$.
:::
:::

::: check
given: fs = 8 | 16 | 48; d = 5 | 20 | 50
answer: 2*fs*1e3/d
tolerance: 0.5%

## Tones {d} Hz apart, sampled at {fs} kHz, must be separated with a Hann window. What's the shortest window, in samples, whose main-lobe half-width $2f_s/L$ is at most {d} Hz?

::: right
Right. $L \ge 2f_s/\Delta f$ = {answer}.
:::

::: misses
- [fs*1e3/d] With a Hann window, the main lobe reaches two bins each side.
- [any] Not yet. Solve $2f_s/L = \Delta f$ for $L$.
:::
:::

::: check
given: b = 100 | 1000 | 1e4 | 1e6
answer: 1/sqrt(b)*1e3
unit: ms
tolerance: 0.5%

## A chirp sweeps {b} Hz per second. About what window length shows it most sharply?

::: right
Right. $T \approx 1/\sqrt\beta$ = {answer}.
:::

::: misses
- [1/b*1e3] Balance $\beta T$ against $1/T$: it's a square root.
- [any] Not yet. Set $\beta T = 1/T$.
:::
:::

::: check
given: L = 128 | 512 | 2048; fs = 8 | 48
answer: L/(fs*1e3)*1e3
unit: ms
tolerance: 0.5%

## How long is an {L}-sample frame at {fs} kHz?

::: right
Right. $L/f_s$ = {answer}: events are located to about this.
:::

::: misses
- [fs*1e3/L] That's the bin spacing in Hz, not the frame length.
- [any] Not yet. $L/f_s$.
:::
:::

::: check
kind: choice

## A spectrogram's frames are zero-padded from 256 to 4096 points before the DFT. What changes?

- [x] The frequency axis is sampled more finely, but two close tones are no easier to separate
- [ ] The frequency resolution improves sixteenfold
- [ ] The time resolution improves
- [ ] Nothing at all, since the padded values are zero

::: right
Right. Zero-padding interpolates the same windowed spectrum at more points; the main lobe's width is set by the 256-sample window, so resolution is unchanged. It does make peaks easier to read off.
:::

::: misses
- [2] Resolution depends on the window's length, which hasn't changed.
- [3] The frame still covers 256 samples of the signal.
- [4] The plotted spectrum gets smoother, which helps locate peaks.
:::
:::

::: check
kind: python
given: b = 2000 | 8000; L = 64 | 256 | 1024

## Track a chirp with a spectrogram. At `fs = 8000`, the signal is `x = cos(2*pi*(500*t + b*t**2/2))` for one second (`t = n/fs`), so its frequency is `500 + b*t` Hz. With Hann frames of `L` = {L} samples, hop `L//2`, find each frame's peak bin, convert it to Hz with `k*fs/L`, and compare with the true frequency at the frame's center. Set `rms_err` (the RMS tracking error in Hz over all frames) and `frames`.

```python starter
import numpy as np
frames = 1
rms_err = 0.0
```

```python solution
import numpy as np
fs = 8000
t = np.arange(fs) / fs
x = np.cos(2 * np.pi * (500 * t + b * t**2 / 2))
H = L // 2
w = np.hanning(L)
errs = []
for m in range((len(x) - L) // H + 1):
    seg = x[m * H:m * H + L] * w
    k = np.argmax(np.abs(np.fft.rfft(seg)))
    tc = (m * H + L / 2) / fs
    errs.append(k * fs / L - (500 + b * tc))
frames = len(errs)
rms_err = float(np.sqrt(np.mean(np.square(errs))))
```

```python tests
import numpy as np
fs = 8000
t = np.arange(fs) / fs
x = np.cos(2 * np.pi * (500 * t + b * t**2 / 2))
H, w, e = L // 2, np.hanning(L), []
for m in range((len(x) - L) // H + 1):
    k = np.argmax(np.abs(np.fft.rfft(x[m * H:m * H + L] * w)))
    e.append(k * fs / L - (500 + b * (m * H + L / 2) / fs))
assert frames == len(e), f"There should be {len(e)} frames."
assert abs(rms_err - np.sqrt(np.mean(np.square(e)))) < 1e-9, "rms_err should be the RMS of the peak-frequency errors."
```

::: right
Right. Short frames leave coarse bins and long frames smear the sweep. Try all three lengths: the error is smallest near $f_s/\sqrt\beta$ samples, the chirp-optimal window in samples.
:::
:::

::: explain
## A technician uses a spectrogram to find an intermittent 2 ms glitch on a motor drive's current, and also to tell apart two vibration tones 3 Hz apart. Why can't one window setting do both, and what should they do?

::: model
A spectrogram's time and frequency resolution trade against each other: a frame of length $T$ locates events to about $T$ and separates frequencies only about $2/T$ apart with a Hann window. Seeing a 2 ms glitch needs frames of a few milliseconds, which blur frequency over hundreds of hertz; separating tones 3 Hz apart needs frames of about two-thirds of a second, which smear any 2 ms event across the whole frame. No single frame length meets both, because their product is fixed. The technician should make two spectrograms with different window lengths, or use a long DFT for the steady tones and a short-window or time-domain analysis for the glitch.
:::
:::

::: practice

::: check
given: fs = 22.05 | 96; L = 2048 | 8192
answer: fs*1e3/L
unit: Hz
tolerance: 0.5%

## What's the bin spacing of {L}-sample frames at {fs} kHz?

::: misses
- [L/(fs*1e3)] That's a time.
- [any] $f_s/L$.
:::
:::

::: check
given: N = 4000 | 10000; L = 400 | 1000
answer: floor((N - L)/(L/2)) + 1
tolerance: 0.1%

## How many 50%-overlapped frames of {L} samples fit in {N} samples?

::: misses
- [floor(N/L)] Frames start every $L/2$ samples.
- [any] $\lfloor(N - L)/(L/2)\rfloor + 1$.
:::
:::
:::
