← All Labs
IDEA #31 · SPECTRAL ANALYSIS — FROM WAVEFORM TO SPECTRUM

Spectral analysis — every signal is a sum of sinusoids

A wiggling line in time hides a simple secret: it is built by adding up pure sine waves, each with its own frequency and loudness. The Fourier transform is the machine that reads that recipe back off the signal. The four tabs below share one signal you build (or draw) once, then view through four lenses — its live spectrum, the effect of a window, a scrolling spectrogram, and what a filter does to it. Every FFT is computed for real, in the browser, on the actual samples.

SHARED SIGNAL
Set the partials in Tab 1 — every tab reads the same signal (spectrogram has its own live source).
TAB 1 · THE RECIPE
Time ↔ frequency
A live signal beside its FFT bar spectrum, updating as you dial the partials.
TAB 2 · THE LEAK
Windowing
The same signal through rectangular / Hann / Hamming windows — watch leakage.
TAB 3 · THE WATERFALL
Spectrogram
A scrolling time–frequency map of a synthesized chirp, or your microphone.
TAB 4 · THE SCULPTOR
Filters
Low / high / band-pass sliders reshape the spectrum and rebuild the wave.
01

Drive it — build a signal, read its spectrum

Dial three partials (frequency + amplitude) and a pinch of noise. The top panel is the waveform in time; the bottom is its FFT magnitude spectrum in frequency. Each spike in the spectrum is one sinusoid you added.
DRIVE IT
TIME DOMAIN  ·  amplitude vs. sample
FREQUENCY DOMAIN  ·  |X(f)| vs. frequency
FFT   N = 1024
waveform (time) spectrum (frequency) detected peaks
FREQUENCY
AMPLITUDE
FREQUENCY
AMPLITUDE
FREQUENCY
AMPLITUDE
NOISE
PEAK 1
Hz
PEAK 2
Hz
PEAK 3
Hz
Sample rate Fs
1000 Hz
Window length N
1024
Bin spacing Δf
Nyquist limit
500 Hz
02

Walkthrough

WALKTHROUGH
1
Start with just Partial 1. The waveform is a clean sine and the spectrum is a single spike at that frequency. One sinusoid → one line. That is the atom of everything here.
2
Raise Partial 2. The waveform gets a wobble — a beat — but the spectrum simply grows a second spike. The messy-looking time signal is just two clean lines in frequency.
3
Drag Partial 2's frequency slowly. Watch its spike slide sideways in the spectrum while its height (amplitude) stays put. Frequency is horizontal position; amplitude is height.
4
Push a frequency past 500 Hz — you can't. That is the Nyquist limit, half the sample rate: the fastest wiggle 1000 samples/second can honestly represent.
5
Add noise and switch the spectrum to Decibel. The spikes still tower over a low, grassy floor — the FFT pulls periodic structure out of the mess. That is what spectral analysis is for.
03

Aha

AHA
THE INSIGHT
A complicated wiggle in time and a handful of spikes in frequency are the same object, written in two alphabets. The FFT is just the translator — and the frequency spelling is often the simpler one.
04

Explanation

EXPLANATION

A signal is a list of numbers sampled in time — here, 1024 amplitude readings taken at 1000 samples per second. Fourier's claim is that any such list can be written as a sum of pure cosines and sines of different frequencies. The Discrete Fourier Transform (DFT) computes exactly how much of each frequency is present.

For each candidate frequency, the DFT multiplies the signal by a sine and a cosine at that frequency and adds up the result. If the signal contains that frequency, the products line up and the sum is large; if it doesn't, positives and negatives cancel and the sum is near zero. The magnitude of that complex sum is the height of the spike you see.

The frequencies it tests are not arbitrary. With N samples at rate Fs, the DFT reports N/2 usable frequencies spaced Δf = Fs/N apart — the bins. Finer frequency resolution needs a longer recording.

The FFT (Fast Fourier Transform) is not a different answer — it is the same DFT computed cleverly. A naive DFT costs about N² multiplications; the FFT factors the problem recursively into N·log₂N, which for N = 1024 is roughly a 100× speed-up. That single algorithm is why real-time spectra, MP3s, JPEGs, Wi-Fi and MRI reconstruction are practical.

The Nyquist–Shannon limit says a sample rate Fs can only represent frequencies below Fs/2. Try to encode something faster and it aliases — it masquerades as a lower frequency, indistinguishable after sampling. That is why the sliders here stop at 500 Hz.

Everything you see is symmetric: the same information sits in the waveform and in the spectrum, so the transform is invertible. Tab 4 uses that inverse to rebuild a wave after editing its spectrum.

05

Research note

RESEARCH NOTE
The discrete Fourier transform and its bin frequencies:
$$X_k=\sum_{n=0}^{N-1}x_n\,e^{-i\,2\pi kn/N},\qquad f_k=\frac{k\,F_s}{N},\quad k=0,1,\dots,\tfrac{N}{2}$$
$$|X_k| \ \text{is the spike height};\qquad f_{\max}=\frac{F_s}{2}\ \text{(Nyquist)}$$
Go deeper: the DFT is the finite, sampled cousin of the continuous Fourier transform; the FFT (Cooley–Tukey, 1965) computes it in O(N log N). For the continuous-drawing view of "frequency space is the picture," see the repo's fourier-epicycles-drawing-name lab; for the sharp-in-one-domain-blurry-in-the-other trade-off, see fourier-uncertainty-tradeoff.
01

Drive it — the same signal, through a window

Before the FFT, the signal is multiplied by a window that tapers its ends to zero. The top panel shows the signal (grey) and the window's taper (purple); the bottom shows the resulting spectrum in dB. Slide the tone between bins to reveal spectral leakage.
DRIVE IT
WINDOWED SIGNAL  ·  taper applied to the ends
SPECTRUM (dB)  ·  main lobe + side lobes
leakage
raw signal window taper spectrum
FREQUENCY
SECOND, WEAKER TONE
ITS AMPLITUDE (dB down)
Nearest bin
Off-bin by
Main-lobe width
Peak side lobe
02

Walkthrough

WALKTHROUGH
1
Keep the window on Rect and press Snap to a bin. The tone lands exactly on a DFT frequency and the spectrum is a single clean spike — no leakage.
2
Now press Sit between bins. The same tone smears into a wide skirt of side lobes. Nothing changed about the signal — only its alignment to the bin grid. This is spectral leakage.
3
Switch to Hann. The skirt collapses: side lobes drop far below the peak. The taper stopped the FFT from seeing an abrupt cut at the ends of the record.
4
Turn up the second, weaker tone and move it close to the first. On Rect the strong tone's leakage buries it; on Hann/Blackman it reappears as its own peak.
5
Compare main-lobe width and peak side lobe across windows. Rect has the narrowest lobe but the worst side lobes; Blackman the reverse. There is no free lunch — only a trade.
03

Aha

AHA
THE INSIGHT
The FFT assumes your recording loops forever. If the ends don't match, it sees a jump — and a jump is broadband. A window tapers the ends so the loop is seamless, trading a little frequency sharpness for a lot less smear.
04

Explanation

EXPLANATION

The DFT does not analyse your signal in isolation — it implicitly treats the N samples as one period of a periodic signal, repeated forever. If a sinusoid completes a whole number of cycles inside the window, the wrap-around is seamless and its energy lands in exactly one bin. If it completes a fractional number of cycles, the loop point has a discontinuity, and a discontinuity contains energy at all frequencies. That smear is spectral leakage.

A window function w[n] multiplies the signal so it fades smoothly to zero at both ends. Now the periodic extension has no jump, so the leakage collapses. The cost is that multiplying in time is convolving in frequency: every true spike is replaced by a blurred copy of the window's own spectrum, the main lobe, flanked by side lobes.

Windows differ in how they split the difference. The rectangular window (no taper) has the narrowest main lobe — best frequency resolution — but side lobes only ~13 dB down, so nearby weak tones drown. Hann and Hamming widen the main lobe roughly 2× but push side lobes to ~-31 dB and ~-43 dB. Blackman goes further still (~-58 dB) at the cost of an even wider lobe.

The rule of thumb: choose a window by what you need to see. To separate two tones of similar strength that are close in frequency, favour a narrow main lobe (rectangular or Hann). To find a faint tone next to a loud one, favour low side lobes (Blackman). This resolution-versus-dynamic-range trade is the whole art of windowing.

05

Research note

RESEARCH NOTE
The common windows applied here, for n = 0…N−1:
$$w_{\text{Hann}}[n]=0.5-0.5\cos\!\frac{2\pi n}{N-1},\qquad w_{\text{Hamming}}[n]=0.54-0.46\cos\!\frac{2\pi n}{N-1}$$
$$w_{\text{Blackman}}[n]=0.42-0.5\cos\!\frac{2\pi n}{N-1}+0.08\cos\!\frac{4\pi n}{N-1}$$
Go deeper: Fredric Harris's 1978 survey "On the Use of Windows for Harmonic Analysis with the DFT" is the canonical catalogue of window trade-offs. The convolution-in-frequency picture is the same duality behind the repo's fourier-uncertainty-tradeoff lab: narrow in time ⇒ wide in frequency.
01

Drive it — watch frequency change over time

A spectrogram stacks one FFT per instant into a scrolling waterfall: time runs left-to-right, frequency bottom-to-top, and colour is loudness. Play a synthesized chirp (a rising/falling sweep) or feed your microphone and watch your voice paint bands.
DRIVE IT
SPECTROGRAM  ·  time → , frequency ↑ , colour = dB
source chirp
LIVE SPECTRUM  ·  the newest column
quiet medium loud peak
SWEEP LOW
SWEEP HIGH
SWEEP PERIOD
SCROLL SPEED
DYNAMIC RANGE
Current tone
FFT size
1024
Columns held
The Microphone source asks the browser for mic permission and runs a native AnalyserNode FFT. Try whistling a slide, or say "eee" then "ooo" and watch the formant bands shift.
02

Walkthrough

WALKTHROUGH
1
Leave the source on Chirp. A single bright trace slides diagonally — the tone is climbing in frequency as time moves right. A pure tone would be a flat horizontal line; a sweep is a ramp.
2
Shorten the sweep period. The diagonal steepens — the same span of frequency crossed in less time. The slope of a spectrogram trace is how fast pitch changes.
3
Switch to Rising tones: instead of a smooth ramp you get a staircase of flat segments — discrete notes, each a horizontal band held for a moment.
4
Try Warble and watch the trace wiggle up and down — vibrato. Now widen the dynamic range and faint harmonics (parallel bands above the main one) fade into view.
5
Pick Microphone and allow access. Whistle a glide and you'll draw your own chirp; speak and you'll see stacked harmonic bands — the signature of a voiced sound.
03

Aha

AHA
THE INSIGHT
A single spectrum is a photograph; a spectrogram is the movie. By taking one FFT per slice of time and stacking them, you can literally see a sound's pitch move — which is why it's the picture behind birdsong, speech, and music transcription.
04

Explanation

EXPLANATION

A plain FFT gives one spectrum for the whole recording — it tells you which frequencies are present but not when. For a sound that changes, like speech or a siren, that is not enough. The fix is the Short-Time Fourier Transform (STFT): chop the signal into short, overlapping frames, window each one, and FFT them separately. Each frame becomes one vertical column of the spectrogram.

Stack the columns left to right and you get a time–frequency image: horizontal axis time, vertical axis frequency, and brightness (or colour) the magnitude in that frame and bin — usually shown in decibels so quiet detail survives. A steady tone draws a horizontal line; a sweep draws a slope; a click draws a vertical streak.

The STFT forces a choice. A long frame gives fine frequency resolution but blurs time — you can't say exactly when a note started. A short frame localises events in time but smears them in frequency. This is the same time–frequency uncertainty that limits every joint measurement; you cannot be perfectly sharp in both at once.

Spectrograms are everywhere: they reveal the formant bands that distinguish vowels, let ornithologists identify birds by the shape of their song, drive Shazam-style audio fingerprinting, and — as a mel-spectrogram — are the standard input that speech-recognition and music neural networks actually "see." Your microphone here runs the browser's built-in analyser doing exactly this, in real time.

05

Research note

RESEARCH NOTE
The short-time Fourier transform — an FFT of a windowed slice around each time m:
$$\text{STFT}\{x\}(m,k)=\sum_{n=0}^{N-1} x[n+mH]\,w[n]\,e^{-i\,2\pi kn/N}$$
$$\text{spectrogram}(m,k)=\big|\text{STFT}\{x\}(m,k)\big|^2,\qquad H=\text{hop size}$$
Go deeper: the frame-length dilemma is a direct instance of the Gabor limit — see the repo's fourier-uncertainty-tradeoff lab. Perceptually warped versions (the mel-spectrogram and MFCCs) are the front end of nearly every modern speech and audio model.
01

Drive it — reshape the spectrum, rebuild the wave

A filter keeps some frequencies and rejects others. Drag the cutoffs and the filter's response (purple) multiplies the spectrum; the surviving frequencies are then inverse-transformed back into a new waveform. Editing frequency, then returning to time, is the whole idea of filtering.
DRIVE IT
SPECTRUM  ·  original (grey) · filter (purple) · kept (orange)
band-pass
RECONSTRUCTED WAVEFORM  ·  inverse FFT of what survived
original spectrum filter response filtered output
CUTOFF / CENTRE
BANDWIDTH
ROLL-OFF SHARPNESS
KEPT
% energy
CUT
% energy
BAND
Hz kept
02

Walkthrough

WALKTHROUGH
1
Start on Low-pass and drag the cutoff down. The purple response is 1 below the cutoff and 0 above; every spike past it is erased and the rebuilt waveform gets smoother — high frequencies were the wiggles.
2
Switch to High-pass. Now the slow, tall spike vanishes and only the fast ripple survives — the waveform loses its baseline sway and keeps its fine texture.
3
Choose Band-pass and narrow the bandwidth. You isolate a single tone: the output becomes a near-perfect sine, whatever the input was. This is how a radio picks one station.
4
Set the input to Tone in noise and band-pass around the tone. The noise floor is slashed while the tone stays — filtering as denoising.
5
Lower the roll-off sharpness. The filter edges soften from a cliff to a ramp; a gentler filter rings less in time but lets more neighbours leak through. Another trade.
03

Aha

AHA
THE INSIGHT
Filtering looks like a hard job in time — but in frequency it's just multiplication: keep these spikes, delete those. Transform, multiply by a mask, transform back. Tuning a radio, brightening a photo, and removing hum are all the same three steps.
04

Explanation

EXPLANATION

A filter selectively passes or rejects frequency components. In the time domain that operation is convolution — a smearing of the signal against the filter's impulse response — which is fiddly. The convolution theorem says that the same operation is plain multiplication in the frequency domain. So the easy recipe is: FFT the signal, multiply the spectrum by the filter's response curve, and inverse-FFT back to time. That is exactly the pipeline running here.

The four archetypes are just different masks: a low-pass keeps frequencies below a cutoff, a high-pass keeps those above, a band-pass keeps a middle band, and a notch deletes one narrow band while keeping the rest. Cascade them and you can carve any shape you like.

Real filters are never perfect bricks. The roll-off sharpness here sets how steeply the response falls at the edge. A brick-wall filter (infinitely sharp) is ideal in frequency but rings badly in time — its impulse response is an endless sinc that smears clicks into long wobbles. A gentle slope rings less but blurs the frequency boundary. This sharpness-versus-ringing tension is the same time–frequency trade seen throughout these tabs.

Because we edit the whole spectrum at once and transform back, this is a zero-phase, frequency-domain filter — clean for teaching. Streaming systems instead use recursive IIR or tapped FIR filters that work sample-by-sample, but the intent is identical: shape the spectrum. Filtering underlies equalisers, noise reduction, radio tuning, anti-alias front-ends, and the sharpen/blur of image editing.

05

Research note

RESEARCH NOTE
The convolution theorem — filtering is multiplication in frequency:
$$y[n]=(x * h)[n]\ \ \Longleftrightarrow\ \ Y_k = X_k\cdot H_k$$
$$y = \mathcal{F}^{-1}\big\{\,\mathcal{F}\{x\}\cdot H\,\big\}\qquad(H=\text{filter response})$$
Go deeper: the ideal brick-wall filter's impulse response is the sinc function, whose infinite ringing is why practical designs (Butterworth, Chebyshev, FIR windows) trade sharpness for behaviour in time. The window functions of Tab 2 are themselves low-pass filters in disguise — see fourier-uncertainty-tradeoff.
Idea #31 · Spectral analysis — from waveform to spectrum · single self-contained HTML · Canvas + Web Audio API + KaTeX · one shared signal across four tabs, real FFTs throughout.