CodeRigor

LESSON

Capstone: rebuild a sound from its partials

Pick the sinusoids out of a windowed frame with interpolated peaks, find the pitch even without its fundamental, and synthesize the sound again.

A steady note is, to a good approximation, a handful of sine waves whose frequencies are whole multiples of one pitch. This lesson takes one frame of a sound apart into those partials and adds them back together, using the DFT, windows and measured filters from the earlier lessons. This lesson pairs with Coding Adventure: Additive Synthesis and Coding Adventure: Analyzing Audio by Sebastian Lague, linked under Watch & read. The first covers building sounds from sine waves with envelopes and harmonics, the second the short-time Fourier transform, windows and spectrograms. You build six NumPy functions that find a frame's partials, estimate its pitch, measure its loudness curve, synthesize a sound and compare two sounds.

A partial is a triple: a frequency fₕ in Hz, an amplitude aₕ and a phase φₕ. The sound is the sum of aₕ cos(2π fₕ t + φₕ). The analysis must turn every number the DFT gives you back into those three units.

Analysis: from one frame to partials
start / 6
Each box is one decision in partials. The window and the centring change the numbers you read; the scale and the interpolation turn them back into Hz and amplitude.
Analysis: from one frame to partials
Each box is one decision in partials. The window and the centring change the numbers you read; the scale and the interpolation turn them back into Hz and amplitude.

Start with the amplitude. A window multiplies the frame by weights between 0 and 1, so the peak it leaves is smaller than the sine that went in. For a Hann window the average weight is one half, and a sine of amplitude A peaks at A · Σw / 2. Multiplying the magnitudes by 2 / Σw gives amplitude units back.

Python
import numpy as np

n = 1024
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)
print(round(w.sum() / n, 3))
for bins in (100.0, 100.5):
    x = np.cos(2 * np.pi * bins * np.arange(n) / n)
    print(bins, round(np.abs(np.fft.rfft(x * w)).max() * 2 / w.sum(), 4))

A tone on a bin reads 1.0, but one halfway between two bins reads 0.8488, because neither bin sits on the top of the peak. Reading the largest bin costs up to 15 percent of the amplitude and half a bin of frequency. Instead, treat the three bins around a peak as samples of a smooth curve. With a, b, c the logarithms of the left, middle and right magnitudes, the parabola through them peaks at k + ½ (a - c) / (a - 2b + c) bins, and its height there, exp(b - ¼ (a - c) shift), is the better amplitude.

Python
import numpy as np

n = 1024
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)
x = np.cos(2 * np.pi * 100.3 * np.arange(n) / n)
mag = np.abs(np.fft.rfft(x * w)) * 2 / w.sum()
k = int(mag.argmax())
a, b, c = np.log(mag[k - 1 : k + 2])
shift = 0.5 * (a - c) / (a - 2 * b + c)
print(k, mag[k - 1 : k + 2].round(4).tolist())
print(round(k + shift, 3), round(float(np.exp(b - 0.25 * (a - c) * shift)), 4))

The true tone is at 100.3 bins with amplitude 1. The parabola gives 100.316 and 1.0145. A Hann peak is not a parabola, so some error is left, and the chart shows how much: almost 4 percent in the worst case. Zero-padding the frame to twice its length puts a bin between each pair, keeps every tone close to a bin top, and cuts the worst case to about a tenth of a percent.

Amplitude error against where the tone falls
A tone at 300 bins plus the offset on the x axis, window gain already removed. Reading the biggest bin costs up to 15 percent, a parabola alone up to 3.8 percent, and a parabola on a frame padded to twice its length at most 0.11 percent.
Amplitude error against where the tone falls
A tone at 300 bins plus the offset on the x axis, window gain already removed. Reading the biggest bin costs up to 15 percent, a parabola alone up to 3.8 percent, and a parabola on a frame padded to twice its length at most 0.11 percent.

Now the phase. The FFT measures phase from index 0, the first sample, so a tone with phase φ at the middle of the frame appears shifted by 2π f · n / (2 · rate) radians. Move the middle of the frame to index 0 before the FFT instead. The window is symmetric about the middle, so its transform is real and positive across the main lobe, and the angle of the peak bin is the phase at the middle. Synthesis uses the same convention: time 0 of the rebuilt sound is the middle of the analysed frame.

Python
import numpy as np

n, k = 1024, 101
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)
x = np.cos(2 * np.pi * k * (np.arange(n) - n // 2) / n + 0.7)   # phase 0.7 at the middle
print(round(float(np.angle(np.fft.rfft(np.roll(x * w, -n // 2))[k])), 3))
print(round(float(np.angle(np.fft.rfft(x * w)[k])), 3))

The loudest partial is not the pitch. Many instruments have a weak or missing first harmonic, yet the ear hears the spacing. Try f / d as a candidate for every partial f and every d from 1 to 8. A candidate scores the summed amplitude of the partials within 3 percent of a whole multiple of it. Subharmonics also divide every partial, so take the highest candidate within 90 percent of the best score, then refine it with a weighted fit of fₕ = h · f₀.

Python
import numpy as np

freqs = np.array([600.0, 800.0, 1000.0, 1200.0])    # harmonics 3 to 6 of 200 Hz
amps = np.array([0.5, 0.33, 0.25, 0.2])
for f0 in (100.0, 200.0, 300.0, 400.0, 600.0):
    ratio = freqs / f0
    hit = np.abs(ratio - np.round(ratio)) <= 0.03
    print(f0, round(float(amps[hit].sum()), 2))

Both 100 Hz and 200 Hz score 1.28, while the others explain only some partials. The higher one, 200 Hz, is right even though no energy sits there. One limit is built in: partials at 2, 4 and 6 times f₀ look like partials at 1, 2 and 3 times 2f₀, and the function reports the higher pitch.

The loudness curve is block-wise: take each block's root-mean-square, scale so the loudest is 1, and put each value at the block's middle time. synthesize multiplies the sum of partials by that curve with np.interp and skips any partial at or above half the sampling rate, which would alias. similarity compares the logs of two windowed magnitude spectra, in dB, over the bins within 60 dB of the loudest.

Two mistakes dominate. Forgetting the window's gain leaves every amplitude at about half, with pitch and frequencies right, so a quick listen hides it. Reading the phase at sample 0 instead of the middle returns right frequencies and amplitudes but a rebuilt waveform shifted against the original. The first changes the spectrum, so similarity sees it. The second barely changes a magnitude, so only a test against the waveform catches it.

The tests build tones with known partials and demand frequencies within 0.5 Hz, amplitudes within 2 percent, phases within 0.02 radians, a pitch found with the first harmonics removed, and a rebuilt waveform that matches the original half-frame. That proves the code on clean, stationary sums of sines, not on real sounds. Vibrato or a fast decay moves a partial inside the frame, noise has no partials, partials closer than about four bins merge into one peak, and a partial far below a loud neighbour can be buried under the window's side lobes. A small spectral distance also says nothing about how the sounds are heard.

Watch & read

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

Builds sounds by adding sine waves, with envelopes for the loudness of each note and sets of harmonics for the timbre of instruments. The synthesis half of this lesson: watch it for the idea, then write synthesize here.

Covers the short-time Fourier transform, the trade between time and frequency resolution, the Hann window and spectrograms. The analysis half of this lesson: it is the frame you take apart in partials.