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.
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.
1import matplotlib.pyplot as plt2import numpy as np34RATE = 160005SECONDS = 4.0678def 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)1213 # 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.551617 tone = np.sin(2 * np.pi * 880.0 * t) * 0.2818 tone[t < SECONDS / 2] = 0.01920 hiss = rng.normal(0.0, 0.02, t.size).astype(np.float32)2122 # 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)252627t, signal = make_signal()28spectrum = np.abs(np.fft.rfft(signal))29freqs = np.fft.rfftfreq(signal.size, 1 / RATE)3031fig, (top, bottom) = plt.subplots(2, 1, figsize=(10, 5.4), constrained_layout=True)3233top.plot(t, signal, linewidth=0.35, color="#2f6fd0")34top.set_title("the waveform", fontsize=10)35top.set_xlabel("seconds")36top.set_xlim(0, SECONDS)3738bottom.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)4243for ax in (top, bottom):44 for side in ("top", "right"):45 ax.spines[side].set_visible(False)46plt.show()
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.
1import base642import io3import wave456def 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) // hop10 out = np.empty((frames, n_fft // 2 + 1), dtype=np.float32)11 for i in range(frames):12 start = i * hop13 out[i] = np.abs(np.fft.rfft(x[start:start + n_fft] * window))14 return out151617def 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")262728_, sound = make_signal()29power = 20 * np.log10(stft(sound) + 1e-6)3031fig, 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()4243display(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)
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.Cliverso serve chirp-spectrogram.versoWhat 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.