Audio Spectra and Pitch
Musical sounds are nearly periodic, so their spectra are combs of harmonics at multiples of a fundamental frequency . The pitch we hear corresponds to , and the timbre to the pattern of harmonic amplitudes. This lesson builds synthetic notes, estimates their pitch with the FFT and with autocorrelation, and maps frequencies to musical notes.
Notes and frequencies
In twelve-tone equal temperament, note semitones above A4 has frequency
so an octave doubles the frequency and a semitone multiplies it by . MIDI note numbers use .
import numpy as np
names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def note_name(f):
p = 69 + 12 * np.log2(f / 440)
k = int(round(p))
cents = 100 * (p - k)
return f"{names[k % 12]}{k // 12 - 1}", round(float(cents), 1) + 0.0
for f in (261.63, 440.0, 329.6, 98.0, 1000.0):
print(f"{f:7.2f} Hz -> {note_name(f)}") 261.63 Hz -> ('C4', 0.0)
440.00 Hz -> ('A4', 0.0)
329.60 Hz -> ('E4', -0.1)
98.00 Hz -> ('G2', 0.0)
1000.00 Hz -> ('B5', 21.3)
Cents measure the remaining distance: 100 cents per semitone, and trained ears notice about 5 cents.
Pitch from the spectrum
Build a note with harmonics, find the spectral peaks, and take the fundamental. The FFT's resolution limits the accuracy, so we refine the peak by fitting a parabola through the three bins around it (a standard trick):
import numpy as np
fs = 16000
t = np.arange(0, 0.25, 1 / fs)
f0 = 196.0 # G3, the lowest string of a violin
note = sum(np.sin(2 * np.pi * k * f0 * t) / k for k in range(1, 9)) * np.exp(-3 * t)
N = len(note)
w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N) / N)
A = np.abs(np.fft.rfft(note * w, 8 * N))
f = np.fft.rfftfreq(8 * N, 1 / fs)
k = np.argmax(A[f < 400]) # strongest peak below 400 Hz
a, b, c = np.log(A[k - 1:k + 2])
offset = 0.5 * (a - c) / (a - 2 * b + c) # parabolic interpolation in log magnitude
estimate = (k + offset) * fs / (8 * N)
print(f"FFT peak bin: {f[k]:.2f} Hz refined estimate: {estimate:.3f} Hz (true {f0})")
harm = [round(float(f[np.argmax(A * (np.abs(f - h * f0) < 20))]), 1) for h in range(1, 5)]
print("first harmonics found near:", harm)FFT peak bin: 196.00 Hz refined estimate: 196.000 Hz (true 196.0)
first harmonics found near: [196.0, 392.0, 588.0, 784.0]
The missing fundamental and autocorrelation
Telephone lines cut everything below about 300 Hz, yet a male voice at 120 Hz still sounds at 120 Hz: the ear infers the fundamental from the spacing of the harmonics. A spectral peak picker would be fooled, but the autocorrelation, which measures how well the signal matches a delayed copy of itself, peaks at the period regardless:
import numpy as np
fs = 8000
t = np.arange(0, 0.2, 1 / fs)
f0 = 120.0
voice = sum(np.cos(2 * np.pi * k * f0 * t) / k for k in range(3, 12)) # harmonics 3..11 only: no 120 Hz component
A = np.abs(np.fft.rfft(voice))
peak = np.fft.rfftfreq(len(voice), 1 / fs)[np.argmax(A)]
X = np.fft.rfft(voice, 2 * len(voice))
ac = np.fft.irfft(np.abs(X) ** 2)[:len(voice)] # autocorrelation via FFT
lo, hi = int(fs / 500), int(fs / 60) # search periods for 60..500 Hz
lag = lo + np.argmax(ac[lo:hi])
print(f"largest spectral peak: {peak:.1f} Hz (the 3rd harmonic)")
print(f"autocorrelation peak at lag {lag} samples -> pitch {fs / lag:.1f} Hz")largest spectral peak: 360.0 Hz (the 3rd harmonic)
autocorrelation peak at lag 67 samples -> pitch 119.4 Hz
The lag must be a whole number of samples: 67 samples gives 119.4 Hz, and interpolating around the peak would refine it to 120 Hz. The autocorrelation is the inverse FFT of the power spectrum (the Wiener-Khinchin theorem), so it is computed with two FFTs.
In software
- Tuners and pitch trackers use autocorrelation variants (YIN, the McLeod method) or cepstral methods;
librosa.pyinandcrepe(a neural network) are common in Python. - Auto-Tune style pitch correction measures frame by frame and resamples or phase-vocodes the signal.
Exercises
Exercise 1: Frequency of a note
What is the frequency of E5 (7 semitones above A4)?
Answer
About 659.26 Hz.
Solution
Hz.
Exercise 2: Resolution needed
Two notes a semitone apart near 100 Hz differ by about 6 Hz. Roughly how long a frame do you need to separate them with an FFT?
Answer
About 0.2 s or more.
Solution
Resolution is roughly (more with a window, about for Hann), so s with a Hann window, at least s in the best case. Low notes need long frames, which is why bass tuners react slowly.
Exercise 3: Cents between two frequencies (code)
How many cents apart are 440 Hz and 445 Hz?
Answer
About 19.6 cents.
Solution
import numpy as np
print(round(1200 * np.log2(445 / 440), 1))19.6
Test yourself
Raising a note by one octave…
- adds 12 Hz
- doubles its frequency
- multiplies it by
- adds 100 cents
The timbre of an instrument is mostly determined by…
- its fundamental frequency
- the relative amplitudes of its harmonics (and how they evolve)
- the sampling rate
- the phase of the fundamental
Why does autocorrelation find the pitch even without the fundamental?
- it adds the missing harmonic
- the signal still repeats with the fundamental period
- it uses a longer FFT
- it removes noise