01. Sampling and aliasing
A digital audio signal is a sequence of samples taken at a fixed rate: 8 kHz for narrow-band telephone speech, 16 kHz for wide-band speech and most speech recognisers, 44.1 or 48 kHz for music. The sample rate determines which frequencies the samples can represent. Frequencies above that limit are not removed: after sampling they appear at lower frequencies. This notebook shows where they appear, why, and how to prevent it.
Learning outcomes. After working through this notebook you can
state the sampling theorem and compute the Nyquist frequency of a sample rate;
predict the alias frequency of any tone with the folding formula, and measure it with an FFT;
explain why naive decimation and naive waveform synthesis alias, and avoid both with
audio_samples(AudioSamples.resample,square_wave_bandlimited);reconstruct a band-limited signal between its samples with a sinc sum.
import os
import tempfile
import matplotlib.pyplot as plt
import numpy as np
import audio_samples as aus
rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64") # generators default to float32; we ask for float64 throughout
Concept
Sampling reads an analogue signal every \(T\) seconds:
where \(x_a(t)\) is the analogue signal (amplitude in units of full scale) at time \(t\) in seconds, \(n\) is the integer sample index, \(T\) is the sampling period in seconds and \(f_s\) is the sample rate in Hz (samples per second).
Why aliasing happens. For any integer \(m\),
because the extra phase \(2\pi m f_s n T = 2\pi m n\) is a whole number of turns. Here \(f\) is a tone frequency in Hz. Since \(\cos\) is even, \(-f\) gives the same samples too, so the tones \(f\), \(f + m f_s\) and \(m f_s - f\) are indistinguishable once sampled.
Nyquist frequency and the sampling theorem. The highest frequency that is represented unambiguously is the Nyquist frequency
in Hz. If \(x_a\) contains no energy at or above \(f_N\), it is recovered exactly from its samples by sinc interpolation (Whittaker-Shannon):
where \(u\) is a dimensionless time offset in sampling periods (this is NumPy’s np.sinc).
Folding formula. A tone at \(f\) Hz appears after sampling at
where \(f_a\) is the alias frequency in Hz (always between 0 and \(f_N\)) and \(k\) is the nearest integer multiple of the sample rate. Equivalently, the frequency axis is folded at \(0\), \(f_N\), \(f_s\), \(3f_N\), …, which maps every frequency into \([0, f_N]\).
Aliasing occurs in three places:
acquisition: an analogue anti-aliasing filter must remove energy above \(f_N\) before the converter samples;
downsampling: keeping every \(M\)-th sample is sampling again at \(f_s/M\), so content between the output’s and the input’s Nyquist frequencies must be filtered out first;
synthesis: a waveform with jumps (a hard square wave) has harmonics at every odd multiple \(h f_0\) of its fundamental \(f_0\), with amplitudes \(4A/(\pi h)\) for peak amplitude \(A\). Computing it sample by sample samples those harmonics too, and the ones above \(f_N\) fold back as inharmonic tones.
With the library
Generate an 11 kHz tone at 48 kHz, then reduce it to 16 kHz (Nyquist frequency 8 kHz) in two ways: naively, by keeping every third sample (written by hand), and with the library’s resampler at each of its three quality tiers. The folding formula predicts \(|11000 - 1 \cdot 16000| = 5000\) Hz.
Two conventions of this library matter here: AudioSamples.rfft(n_fft) returns magnitudes
\(|X[k]|\) (NumPy’s np.fft.rfft returns complex values), shaped (channels, n_fft // 2 + 1),
and it does not normalise, so a bin-centred sine of amplitude \(A\) gives \(|X[k]| = A N / 2\).
# 250 ms of an 11 kHz tone, amplitude 0.5, at 48 kHz: 12 000 samples.
hi = aus.sine_wave(11_000.0, 0.25, sample_rate=48_000, amplitude=0.5, dtype=F64)
assert hi.samples_per_channel() == 12_000
# Naive decimation, written by hand: keep every third sample -> 4000 samples at 16 kHz.
naive = aus.AudioSamples.new_mono(hi.to_numpy()[::3], sample_rate=16_000)
assert naive.samples_per_channel() == 4000
# A 4000-point DFT of 4000 samples at 16 kHz has 4 Hz bins.
mag = naive.rfft(4000)[0]
peak = int(np.argmax(mag))
assert peak * 4.0 == 5_000.0 # the alias, exactly where predicted
# A bin-centred sine of amplitude A gives |X| = A N / 2 = 0.5 * 4000 / 2 = 1000: full strength.
assert abs(mag[peak] - 1000.0) < 1e-6
# Every ResamplingQuality low-pass filters below 8 kHz before decimating. In the steady state
# (middle 100 ms: 1600 samples, 500 whole periods of 5 kHz) one DFT bin measures what is left of
# the alias, in dB relative to the tone's amplitude of 0.5.
def level_db(y, f, fs, amp):
n = np.arange(len(y))
return 20 * np.log10(2 / len(y) * abs(np.sum(y * np.exp(-2j * np.pi * f * n / fs))) / amp)
mid = slice(1_200, 2_800)
alias_naive = level_db(naive.to_numpy()[mid], 5_000.0, 16_000, 0.5)
tiers = {name: hi.resample(16_000, getattr(aus.ResamplingQuality, name)) for name in ("fast", "medium", "high")}
steady = {name: level_db(y.to_numpy()[mid], 5_000.0, 16_000, 0.5) for name, y in tiers.items()}
print(f"alias at {peak * 4.0:.0f} Hz, |X| = {mag[peak]:.3f}")
print(f"steady state at 5 kHz: naive {alias_naive:+.2f} dB, "
+ ", ".join(f"{name} {v:.1f} dB" for name, v in steady.items()))
assert abs(alias_naive) < 1e-6 # the alias at full strength
assert all(y.samples_per_channel() == 4_000 for y in tiers.values())
# Gone: for this 1 : 3 ratio the resampler drops everything above the output's Nyquist frequency
# in the frequency domain instead of folding its filter's stopband back, so what is left is
# float64 round-off, more than 180 dB down.
assert all(v < -180 for v in steady.values())
# Over the whole 250 ms the largest remaining component of the High output is not the alias:
# the tone is switched on and off abruptly, and those edges leave broadband transients (the
# first 50 output samples reach 0.12) that the filter passes below 8 kHz.
y_high = tiers["high"].to_numpy()
mag_high = tiers["high"].rfft(4000)[0]
edge_db = 20 * np.log10(mag[peak] / mag_high.max())
whole_alias_db = 20 * np.log10(mag[peak] / mag_high[peak])
top_hz = np.argmax(mag_high) * 4.0
print(f"whole signal (High): 5 kHz bin {-whole_alias_db:.1f} dB, largest component {-edge_db:.1f} dB "
f"at {top_hz:.0f} Hz")
# Strongest leftover at 7652 Hz, in the transition band between 0.913 x 8 kHz and 8 kHz.
assert top_hz == 7_652.0 and 0.913 * 8_000 < top_hz < 8_000
assert abs(edge_db - 74.55) < 0.05 and abs(whole_alias_db - 78.4) < 0.05
assert abs(np.abs(y_high[:50]).max() - 0.12) < 0.005
assert np.abs(y_high[mid]).max() < 1e-7
alias at 5000 Hz, |X| = 1000.000
steady state at 5 kHz: naive -0.00 dB, fast -271.9 dB, medium -191.5 dB, high -223.9 dB
whole signal (High): 5 kHz bin -78.4 dB, largest component -74.5 dB at 7652 Hz
freqs = np.arange(mag.size) * 4.0
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(freqs, 20 * np.log10(mag / 1000.0 + 1e-12), label="keep every 3rd sample (naive)")
for name in ("fast", "high"):
spec = tiers[name].rfft(4000)[0]
ax.plot(freqs, 20 * np.log10(spec / 1000.0 + 1e-12), lw=0.8, label=f"ResamplingQuality.{name}")
ax.set(xlabel="Frequency (Hz)", ylabel="Level re full-strength tone (dB)", ylim=(-160, 10),
title="11 kHz tone resampled from 48 kHz to 16 kHz")
ax.legend(loc="lower left")
plt.show()
The naive version did not remove the tone; it moved it to 5 kHz at full strength, where it is
indistinguishable from a genuine 5 kHz component. Every tier of the resampler removes it:
in the steady state (the middle 100 ms) the 5 kHz residue is float64 round-off, more than 180 dB
below the tone, for every tier: for this 1 : 3 ratio the resampler drops everything above the
output’s Nyquist frequency in the frequency domain (notebook 07 measures every tier this way).
Measured over the whole 250 ms the high output appears much
worse: the largest remaining component is only 74.5 dB down and is at 7652 Hz, not 5 kHz, and
the 5 kHz bin is only 78.4 dB down. Both come from the abrupt start and end of the tone, not
from aliasing, so measure alias rejection away from the edges.
The same applies when a waveform is synthesised. A naive square wave (aus.square_wave)
switches between \(\pm A\); the band-limited version (aus.square_wave_bandlimited) adds only the
odd harmonics below \(f_N\). With \(f_0 = 700\) Hz and \(f_s = 16\) kHz, one second holds exactly 700
periods, so every harmonic and every alias falls on an integer-Hz bin of a 16 000-point DFT, and
we can count the power that is not at an odd harmonic of 700 Hz.
s_naive = aus.square_wave(700.0, 1.0, sample_rate=16_000, dtype=F64).rfft(16_000)[0] # 1 Hz bins
s_clean = aus.square_wave_bandlimited(700.0, 1.0, sample_rate=16_000, dtype=F64).rfft(16_000)[0]
k = np.arange(s_naive.size)
odd_harmonic = (k % 700 == 0) & ((k // 700) % 2 == 1)
def stray_db(s):
# Power not at an odd harmonic of 700 Hz, relative to the total, in dB.
return 10 * np.log10((s[~odd_harmonic] ** 2).sum() / (s ** 2).sum())
print(f"stray power: naive {stray_db(s_naive):.2f} dB, band-limited {stray_db(s_clean):.1f} dB")
# About 3.3 % of the naive wave's power is aliased (-14.77 dB) ...
assert abs(stray_db(s_naive) + 14.77) < 0.01
assert abs(10 ** (stray_db(s_naive) / 10) - 0.033) < 0.0005
# ... and almost none of the band-limited wave's.
assert stray_db(s_clean) < -200.0
# The 13th harmonic (9100 Hz) is the first above 8 kHz: it folds to 6900 Hz, close to its ideal
# level of 1/13 of the fundamental (-22.3 dB).
rel_db = 20 * np.log10(s_naive[6900] / s_naive[700])
assert abs(20 * np.log10(1 / 13) - (-22.3)) < 0.05
assert abs(rel_db - 20 * np.log10(1 / 13)) < 0.3
assert s_clean[6900] / s_clean[700] < 1e-9
stray power: naive -14.77 dB, band-limited -247.2 dB
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(k, 20 * np.log10(s_naive / s_naive.max() + 1e-12), lw=0.8, label="square_wave (naive)")
ax.plot(k, 20 * np.log10(s_clean / s_clean.max() + 1e-12), lw=0.8, label="square_wave_bandlimited")
ax.set(xlabel="Frequency (Hz)", ylabel="Level re fundamental (dB)", ylim=(-120, 5),
title="700 Hz square wave at 16 kHz: aliased harmonics fill the gaps")
ax.legend(loc="lower left")
plt.show()
The sample rate is stored with the data. Write the 48 kHz tone to a WAV file in a temporary
directory and read it back: the header stores the rate, and the samples are preserved. (A
float64 buffer is stored as a 64-bit float WAV, so it comes back as float64.)
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "tone_11k.wav")
aus.io.save(path, hi)
back = aus.io.read(path)
print(back.sample_rate, back.dtype, back.samples_per_channel())
assert back.sample_rate == 48_000
assert back.samples_per_channel() == hi.samples_per_channel()
# 64-bit float storage keeps every sample, well within this tolerance.
assert np.allclose(back.to_numpy(), hi.to_numpy(), atol=3e-8)
48000 f64 12000
How it works
The folding formula is one line of code. Check it over a sweep of frequencies, and check the identity behind it: the samples of an 11 kHz sine at 16 kHz are exactly those of a 5 kHz sine with inverted sign, because \(\sin(2\pi \cdot 11000\, n/16000) = \sin(2\pi(11000 - 16000)\, n/16000) = -\sin(2\pi \cdot 5000\, n / 16000)\).
def fold(f, fs):
# Alias of a tone at f Hz sampled at fs Hz: |f - round(f / fs) * fs|.
return np.abs(f - np.round(f / fs) * fs)
# Every 250 Hz from 0 to 50 kHz at 16 kHz folds into [0, 8000] Hz.
sweep = 250.0 * np.arange(201)
aliases = fold(sweep, 16_000.0)
assert aliases.max() <= 8_000.0 and aliases.min() >= 0.0
# Measure the alias of a few of them with the library's rfft (0.25 s -> 4 Hz bins; every
# alias below is a multiple of 4 Hz, so it lands exactly on a bin).
for f in [3_000.0, 11_000.0, 25_000.0, 47_200.0]:
t = np.arange(4000) / 16_000.0
x = aus.AudioSamples.new_mono(np.cos(2 * np.pi * f * t), sample_rate=16_000)
assert np.argmax(x.rfft(4000)[0]) * 4.0 == fold(f, 16_000.0)
# Identical samples, sign inverted. Tolerance: sin of arguments up to ~2e4 rad in float64
# carries ~1e-12 of rounding.
n = np.arange(1000)
assert np.allclose(np.sin(2 * np.pi * 11_000 * n / 16_000), -np.sin(2 * np.pi * 5_000 * n / 16_000), atol=1e-9)
The library’s rfft is the magnitude of the ordinary DFT. NumPy is an independent reference with
the same (unnormalised, negative-exponent) convention, once we take np.abs:
sq = aus.square_wave(700.0, 1.0, sample_rate=16_000, dtype=F64)
ref = np.abs(np.fft.rfft(sq.to_numpy(), n=16_000))
# 16 000-term FFT sums of values of size 1: rounding of order 1e-12.
assert np.allclose(sq.rfft(16_000)[0], ref, atol=1e-9)
The sampling theorem says a band-limited signal can be recovered between its samples. Reconstruct a 1 kHz tone sampled at 8 kHz halfway between two samples with a (truncated) sinc sum:
fs, f = 8_000.0, 1_000.0
n = np.arange(8000)
x = np.sin(2 * np.pi * f * n / fs)
u0 = 4000.5 # t = 4000.5 T, in the middle of the 1 s block
estimate = np.sum(x * np.sinc(u0 - n))
truth = np.sin(2 * np.pi * f * u0 / fs)
print(f"sinc reconstruction {estimate:.6f}, true value {truth:.6f}")
# The sum is truncated to 8000 terms; the neglected tails decay like 1/(pi u), so an error of
# order 1e-4 is expected.
assert abs(estimate - truth) < 1e-3
sinc reconstruction 0.382650, true value 0.382683
Ask the library to explain
aus.explain.sampling and aus.explain.aliasing return an ExplainDoc with the formulas, the
values for your parameters, a table of tones that share the same samples, and a warning when a tone is
above the Nyquist frequency. In Jupyter the document renders as Markdown.
s = aus.explain.sampling(16_000.0)
assert s.quantity("Nyquist frequency") == 8_000.0
assert s.quantity("Sampling period") == 0.0625 # in ms
# 8 kHz is below the 20 kHz limit of hearing: an informational note.
assert s.has_warning("info")
s
Sampling
Sampling at 16000 Hz takes one sample every 0.0625 ms. Frequencies below 8000 Hz are represented unambiguously; anything above folds back (aliases) into that range.
Formulas
A sample is the analogue signal read every T seconds:
$$ x[n] = x_a(nT), \quad T = \frac{1}{f_s} $$
Nyquist frequency: the highest representable frequency:
$$ f_N = \frac{f_s}{2} $$
Ideal (Whittaker-Shannon) reconstruction, exact when x_a has no energy at or above f_N:
$$ x_a(t) = \sum_{n} x[n] , \mathrm{sinc}\left(\frac{t - nT}{T}\right) $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $f_s$ | sample rate | 16000 Hz | | $T$ | sampling period | 0.0625 ms | | $f_N$ | Nyquist frequency | 8000 Hz |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Sampling period | $T$ = 0.0625 ms | $T = 1000 / f_s$ | | Nyquist frequency | $f_N$ = 8000 Hz | $f_N = f_s / 2$ | | Samples per millisecond | $f_s / 1000$ = 16 | $f_s / 1000$ |
Trade-offs
A higher sample rate represents more bandwidth but costs proportionally more storage and computation.
Real converters need an analogue anti-aliasing filter whose transition band lies below f_N, so usable bandwidth is somewhat less than f_s/2.
Warnings
Info: The Nyquist frequency (8000 Hz) is below 20 kHz, the nominal upper limit of hearing; content between 8000 Hz and 20 kHz cannot be represented. Hint: Fine for speech; use 44.1 kHz or 48 kHz for full-band music.
See also
Aliasing:
audio_samples::educational::topics::aliasingAliasing (Python):
audio_samples.explain.aliasingSample rate of a signal:
audio_samples::AudioSamples::sample_rateSample rate of a signal (Python):
audio_samples.AudioSamples.sample_ratePython:
audio_samples.explain.sampling
a = aus.explain.aliasing(25_000.0, 16_000.0)
assert a.quantity("Alias frequency") == 7_000.0 == fold(25_000.0, 16_000.0)
assert a.has_warning("caution")
assert a.has_warning_containing("will alias to 7000 Hz")
for w in a.warnings:
print(f"[{w['level']}] {w['message']}")
a
[caution] 25000 Hz is above the Nyquist frequency (8000 Hz) and will alias to 7000 Hz.
Aliasing
A tone at 25000 Hz, sampled at 16000 Hz, produces the same samples as a 7000 Hz tone. Only frequencies up to the Nyquist frequency (8000 Hz) are represented faithfully.
Formulas
Folded (alias) frequency: where the tone appears after sampling:
$$ f_a = \left| f - k f_s \right|, \quad k = \mathrm{round}\left(\frac{f}{f_s}\right) $$
Tones that differ by a multiple of f_s give identical samples:
$$ \cos(2\pi f n T) = \cos(2\pi (f + m f_s) n T), \quad m \in \mathbb{Z} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $f$ | tone frequency | 25000 Hz | | $f_s$ | sample rate | 16000 Hz | | $k$ | nearest multiple of f_s | 2 |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Nyquist frequency | $f_N$ = 8000 Hz | $f_s / 2$ | | Normalised frequency | $f / f_s$ = 1.5625 cycles/sample | $f / f_s$ | | Alias frequency | $f_a$ = 7000 Hz | $\left\vert f - k f_s \right\vert $ |
Analogue frequencies that produce identical samples
| Analogue tone (Hz) | Appears at (Hz) | |—|—| | 7000 | 7000 | | 9000 | 7000 | | 23000 | 7000 | | 25000 | 7000 | | 39000 | 7000 | | 41000 | 7000 |
Trade-offs
Aliasing cannot be undone after sampling: the alias and a genuine tone at f_a are indistinguishable.
Warnings
Caution: 25000 Hz is above the Nyquist frequency (8000 Hz) and will alias to 7000 Hz. Hint: Low-pass filter below 8000 Hz before sampling or downsampling, or sample above 50000 Hz.
See also
Sampling:
audio_samples::educational::topics::samplingSampling (Python):
audio_samples.explain.samplingResampling:
audio_samples::educational::topics::resamplingResampling (Python):
audio_samples.explain.resampling
Exercises
A telephone line samples at 8 kHz. A 7.5 kHz whistle reaches the converter unfiltered. At what frequency (Hz) does it appear? Store it in
answer.
answer = None # TODO
# Solution
answer = fold(7_500.0, 8_000.0) # |7500 - 1 * 8000|
assert answer == 500.0
assert aus.explain.aliasing(7_500.0, 8_000.0).quantity("Alias frequency") == answer
You halve the rate of a 44.1 kHz recording by keeping every second sample. It contains a 15 kHz tone. Predict its alias frequency, then measure it with
rfft(use 0.2 s of signal, so the decimated 4410 samples give 5 Hz bins).
answer = None # TODO
# Solution
answer = fold(15_000.0, 22_050.0) # decimated rate 22 050 Hz: |15000 - 22050|
assert answer == 7_050.0
x = aus.sine_wave(15_000.0, 0.2, sample_rate=44_100, dtype=F64)
dec = aus.AudioSamples.new_mono(x.to_numpy()[::2], sample_rate=22_050)
assert dec.samples_per_channel() == 4410
assert np.argmax(dec.rfft(4410)[0]) * 5.0 == answer
In the naive 700 Hz square wave above there is energy at 1300 Hz, which is not a harmonic of 700 Hz. Which harmonic number \(h\) folded there? Check that the band-limited wave has nothing there.
answer = None # TODO
# Solution
answer = next(h for h in range(1, 200, 2) if fold(700.0 * h, 16_000.0) == 1_300.0)
assert answer == 21 # 14 700 Hz, folded about 16 kHz
assert s_naive[1300] / s_naive[700] > 1e-3 # clearly present
assert s_clean[1300] / s_clean[700] < 1e-9 # absent
Common pitfalls
Keeping every \(M\)-th sample (
x[::M]) is not resampling: it aliases. EveryResamplingQualityfilters first, but the default,fast, uses a short filter whose pass band ends at 0.8 times the output’s Nyquist frequency; passResamplingQuality.mediumor.highwhen the top of the band matters (notebook 07).square_wave,sawtooth_waveandtriangle_waveare naive and alias; use the*_bandlimitedversions for test signals.The generators return
float32unless you passdtype=np.float64(anp.dtypeor a string such as"float64"also works).A tone exactly at \(f_N\) is ambiguous: a sine sampled there at zero phase is all zeros.
An alias may come back with inverted phase (the 11 kHz example returns as \(-\sin\) at 5 kHz).
AudioSamples.rfftreturns magnitudes, unlikenp.fft.rfft; useAudioSamples.fftfor the complex bins.n_fftmust be at least the signal length (notebook 03).
See also
Rust guide chapter: 01. Sampling and aliasing (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) and the labexamples/tutorial_01_sampling_aliasing.rs.Python API:
AudioSamples.resample,ResamplingQuality,AudioSamples.rfft,aus.sine_wave,aus.square_wave_bandlimited,aus.explain.sampling,aus.explain.aliasing,aus.explain.resampling(API reference).Next: 02. Quantisation and dither.
References
Shannon, C. E. (1949). Communication in the presence of noise. Proceedings of the IRE, 37(1), 10-21.
Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Chapter 4 (sampling, aliasing, changing the sampling rate).