Gallery · Signal processing

See a sound, then hear it

A rising chirp, a tone that joins halfway, and a hand-rolled short-time Fourier transform that shows when each arrived. Press play and hear the picture.

chirp-spectrogram.verso Python · 5 cells Read-only preview Download

See a sound, then hear it

A spectrogram is what you get when you stop asking what frequencies a signal contains and start asking when it contained them. It is a stack of short Fourier transforms, one per slice of time.

This builds a signal, transforms it, draws it, and then plays it back, all in numpy and the standard library. No audio package involved.

[1]
codePython
1import matplotlib.pyplot as plt
2import numpy as np
3
4RATE = 16000
5SECONDS = 4.0
6
7
8def make_signal():
9 """A rising chirp, a steady tone that joins halfway, and some hiss."""
10 rng = np.random.default_rng(20260726)
11 t = np.linspace(0.0, SECONDS, int(RATE * SECONDS), endpoint=False, dtype=np.float32)
12
13 # Frequency climbs from 200 Hz to 3.2 kHz, so the phase is the integral of that.
14 sweep = 200.0 + (3000.0 * t / SECONDS)
15 chirp = np.sin(2 * np.pi * np.cumsum(sweep) / RATE) * 0.55
16
17 tone = np.sin(2 * np.pi * 880.0 * t) * 0.28
18 tone[t < SECONDS / 2] = 0.0
19
20 hiss = rng.normal(0.0, 0.02, t.size).astype(np.float32)
21
22 # A slow fade in and out, so playback does not start with a click.
23 envelope = np.minimum(1.0, np.minimum(t, SECONDS - t) / 0.15)
24 return t, ((chirp + tone + hiss) * envelope).astype(np.float32)
25
26
27t, signal = make_signal()
28spectrum = np.abs(np.fft.rfft(signal))
29freqs = np.fft.rfftfreq(signal.size, 1 / RATE)
30
31fig, (top, bottom) = plt.subplots(2, 1, figsize=(10, 5.4), constrained_layout=True)
32
33top.plot(t, signal, linewidth=0.35, color="#2f6fd0")
34top.set_title("the waveform", fontsize=10)
35top.set_xlabel("seconds")
36top.set_xlim(0, SECONDS)
37
38bottom.semilogy(freqs, spectrum + 1e-6, linewidth=0.8, color="#c1440e")
39bottom.set_title("everything it contains, with no idea when", fontsize=10)
40bottom.set_xlabel("Hz")
41bottom.set_xlim(0, 4200)
42
43for ax in (top, bottom):
44 for side in ("top", "right"):
45 ax.spines[side].set_visible(False)
46plt.show()
✓completed

When, not just what

The spectrum underneath the waveform says the signal holds everything from 200 Hz to a bit past 3 kHz, plus something at 880 Hz. True, and useless: it cannot tell you the sweep rises, or that the tone only shows up halfway.

Cut the signal into overlapping slices and transform each one, and the picture answers both questions at once.

[2]
codePython
1import base64
2import io
3import wave
4
5
6def stft(x, n_fft=512, hop=128):
7 """Short-time Fourier transform: one spectrum per slice, Hann-windowed."""
8 window = np.hanning(n_fft).astype(np.float32)
9 frames = 1 + (x.size - n_fft) // hop
10 out = np.empty((frames, n_fft // 2 + 1), dtype=np.float32)
11 for i in range(frames):
12 start = i * hop
13 out[i] = np.abs(np.fft.rfft(x[start:start + n_fft] * window))
14 return out
15
16
17def wav_data_uri(x, rate):
18 pcm = (np.clip(x, -1.0, 1.0) * 32767).astype("<i2")
19 buffer = io.BytesIO()
20 with wave.open(buffer, "wb") as out:
21 out.setnchannels(1)
22 out.setsampwidth(2)
23 out.setframerate(rate)
24 out.writeframes(pcm.tobytes())
25 return base64.b64encode(buffer.getvalue()).decode("ascii")
26
27
28_, sound = make_signal()
29power = 20 * np.log10(stft(sound) + 1e-6)
30
31fig, ax = plt.subplots(figsize=(10, 4.2), dpi=88, constrained_layout=True)
32picture = ax.imshow(
33 power.T, origin="lower", aspect="auto", cmap="magma",
34 extent=(0, SECONDS, 0, RATE / 2), vmin=power.max() - 55, vmax=power.max(),
35)
36ax.set_ylim(0, 4200)
37ax.set_xlabel("seconds")
38ax.set_ylabel("Hz")
39ax.set_title("the sweep is a line, the tone is a ledge", fontsize=10)
40fig.colorbar(picture, ax=ax, label="dB")
41plt.show()
42
43display(
44 '<audio controls style="width:100%;max-width:640px" '
45 f'src="data:audio/wav;base64,{wav_data_uri(sound, RATE)}"></audio>',
46 mime_type="text/html",
47)
✓completed

Make it yours

Press play. The diagonal line is the rising sweep, and the flat ledge at 880 Hz starts exactly where the tone joins, two seconds in. Everything below about 55 dB of the peak is clipped away, which is what turns the hiss into a dark background instead of a wash of noise.

Download the notebook and change n_fft. Larger windows separate the two sounds more sharply in frequency and smear them in time, smaller windows do the reverse. There is no setting that is precise in both, which is the whole tradeoff in one number.

Run it yourself

Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.

dotnet tool install --global Verso.Cli
verso serve chirp-spectrogram.verso

What this shows

A rising chirp, a tone that joins halfway, and a hand-rolled short-time Fourier transform that shows when each arrived. Press play and hear the picture.

Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.