Lesson 1.2Module 1: Music as a time series35 minBeginner
Sampling and aliasing: why a CD measures sound 44,100 times a second
Sound is continuous; a recording is not. See and hear what goes wrong when you measure too slowly: high notes that come back as low ones, and a streaming chart that invents a cycle that isn't there.
A sound wave changes continuously, but a computer can only store snapshots of it. How many snapshots do you need? Take too few and something strange happens: a high note comes back as a different, lower note, and nothing in the data warns you. This lesson is about that effect, called aliasing. It explains why CDs use 44,100 samples a second, and it applies just as much to streaming numbers and economic statistics as to sound.
Continuous sound, sampled data
In lesson 1.1 you built a click track out of 22,050 numbers per second. Each of those numbers is a sample: a measurement of the sound wave at one instant. The sample rate is how many samples you take per second, measured in hertz (Hz).
The sound in the air doesn't come in samples. It's a continuous wave. So every digital recording, every MP3 and every stream is a set of snapshots of something continuous, and the question is what gets lost between the snapshots.
The answer depends on frequency: how many times per second a wave repeats. Frequency is what you hear as pitch. Concert A, the note orchestras tune to, is 440 Hz. A piano's top note is about 4,186 Hz. The hiss of a cymbal reaches well above 10,000 Hz. Human hearing tops out at around 20,000 Hz (20 kHz), less as we get older.
Set up
import wave
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def save_wav(name, x, sr):
"""Save a numpy array as a 16-bit mono WAV file you can play."""
pcm = (x / np.abs(x).max() * 0.8 * 32767).astype(np.int16)
with wave.open(name, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sr)
f.writeframes(pcm.tobytes())Too few snapshots: a wave in disguise
Start with something slow enough to see: a wave that repeats 7 times a second (7 Hz), sampled only 8 times a second.
f_true = 7 # the real wave: 7 cycles per second
fs = 8 # but we only sample 8 times per second
t_fine = np.linspace(0, 2, 2000) # very fine time steps stand in for continuous time
t_s = np.arange(0, 2, 1 / fs) # the instants when we take a sample
plt.figure(figsize=(10, 3.2))
plt.plot(t_fine, np.sin(2 * np.pi * f_true * t_fine), linewidth=1, alpha=0.6, label="The real 7 Hz wave")
plt.plot(t_fine, -np.sin(2 * np.pi * 1 * t_fine), "--", linewidth=2, label="A 1 Hz wave through the same dots")
plt.plot(t_s, np.sin(2 * np.pi * f_true * t_s), "o", markersize=7, color="C2", label="Our samples, 8 per second")
plt.xlabel("Time (seconds)")
plt.title("Sampled too slowly, a 7 Hz wave is indistinguishable from a 1 Hz wave")
plt.legend(loc="upper right", fontsize=8)
plt.show()Every dot sits on the fast 7 Hz wave, and every dot also sits on a slow 1 Hz wave (upside down). The samples alone can't tell the two apart. Anyone rebuilding the sound from these dots will choose the simplest wave that fits, the slow one. The 7 Hz wave has taken on a false identity, an alias, and that's where the name aliasing comes from.
You've seen this effect in films. A film camera takes 24 pictures a second, and a fast-spinning wagon wheel or helicopter rotor can look as if it's turning slowly, or even backwards. The camera samples too slowly for the motion, and the motion comes out disguised.
The rule: half the sample rate
How fast is fast enough? The answer is one of the most important results in signal processing, the sampling theorem, usually credited to Harry Nyquist and Claude Shannon:
If a signal contains no frequencies above half the sample rate, the samples capture it completely. The original continuous wave can be rebuilt exactly from the samples.
Half the sample rate is called the Nyquist frequency. Below it, sampling loses nothing. Above it, frequencies don't disappear. They fold back below the Nyquist frequency and pretend to be something else. You can calculate exactly where they land:
def alias(f, fs):
"""The frequency you actually get when a tone of f Hz is sampled fs times a second."""
return abs(f - fs * round(f / fs))
for f in [440, 5_000, 15_000, 25_000, 30_000, 40_000]:
print(f"{f:>6,} Hz sampled at 44,100 Hz comes out as {alias(f, 44_100):>6,} Hz")At a sample rate of 44,100 Hz the Nyquist frequency is 22,050 Hz. Every tone up to 15,000 Hz comes through unchanged, but a 25,000 Hz tone (above human hearing) comes out as 19,100 Hz, and a 40,000 Hz tone comes out as 4,100 Hz, right in the middle of the audible range. The next chart shows the whole pattern for a sample rate of 8,000 Hz, the rate used by traditional telephone calls:
fs = 8_000
true_f = range(0, 20_001, 10)
plt.figure(figsize=(10, 3.2))
plt.plot(list(true_f), [alias(f, fs) for f in true_f], linewidth=2)
plt.axhline(fs / 2, linestyle=":", color="C2")
plt.text(200, fs / 2 + 150, "Nyquist frequency = 4,000 Hz", color="C2", fontsize=9)
plt.xlabel("The real frequency (Hz)")
plt.ylabel("The frequency you get (Hz)")
plt.title("Sampling at 8,000 Hz folds every frequency into the range 0 to 4,000 Hz")
plt.show()Up to 4,000 Hz the line is a diagonal: what goes in comes out. Beyond that it zigzags, as if the frequency axis were a strip of paper folded back and forth at every multiple of 4,000 Hz. That's why the Nyquist frequency is also called the folding frequency.
Hear it: a rising tone that turns around
Now let's make it audible. A sweep is a tone whose pitch rises steadily, here from 200 Hz to 12,000 Hz over six seconds. We'll create the same sweep twice: once sampled at 44,100 Hz (Nyquist 22,050 Hz, plenty of room) and once at 8,000 Hz (Nyquist 4,000 Hz, far too low).
def sweep(sr, f0=200, f1=12_000, seconds=6):
"""A tone rising steadily from f0 to f1 Hz, sampled sr times a second."""
t = np.arange(int(sr * seconds)) / sr
k = (f1 - f0) / seconds # how fast the pitch rises, in Hz per second
return 0.5 * np.sin(2 * np.pi * (f0 * t + k / 2 * t ** 2))
good = sweep(44_100)
bad = sweep(8_000)
save_wav("sweep_44100.wav", good, 44_100)
save_wav("sweep_8000.wav", bad, 8_000)The second version rises until about 2 seconds, when the real pitch passes 4,000 Hz. Then it falls, even though the real tone is still rising, until it reaches almost nothing at 4 seconds (8,000 Hz). Then it climbs again. That's the zigzag from the chart, played as sound. A spectrogram shows it as a picture: time runs left to right, frequency bottom to top, and brightness shows how strong each frequency is.
fig, ax = plt.subplots(1, 2, figsize=(10, 3.4), sharey=True)
ax[0].specgram(good, NFFT=1024, Fs=44_100, noverlap=768, cmap="magma")
ax[0].set_title("Sampled at 44,100 Hz")
ax[1].specgram(bad, NFFT=256, Fs=8_000, noverlap=192, cmap="magma")
ax[1].set_title("Sampled at 8,000 Hz")
ax[0].set_ylim(0, 13_000)
ax[0].set_ylabel("Frequency (Hz)")
for a in ax:
a.set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()Why 44,100?
Human hearing reaches about 20,000 Hz, so a recording needs a Nyquist frequency above that, which means a sample rate above 40,000 Hz. The extra 2,050 Hz above 20 kHz gives the electronics room to work, as the next section explains.
The exact number, 44,100, is a piece of history. The first digital audio recorders stored their samples on video tape, three samples on each line of the video picture. American-style video has 245 usable lines per field and 60 fields a second, and 3 × 245 × 60 = 44,100. European video gives the same answer (3 × 294 × 50). When the CD was designed around 1980 it inherited the rate from those recorders. Video and film audio later settled on 48,000 Hz, and "high-resolution" audio uses 96,000 Hz or more.
The cure: filter before you sample
Once a frequency has been aliased, it can't be removed. In the samples, a folded-down 40,000 Hz tone is a perfectly ordinary 4,100 Hz tone. So the fix has to come before sampling: an anti-aliasing filter removes everything above the Nyquist frequency first. Every recording device and audio interface has one built in, and the margin between 20,000 Hz and 22,050 Hz is the room that filter needs to cut off smoothly.
The same rule applies whenever you lower the sample rate of a file you already have. The wrong way is to keep every fifth sample. The right way is to remove the high frequencies first, then keep every fifth sample:
step = 5 # keep 1 sample in 5: 44,100 -> 8,820 per second
new_sr = 44_100 // step
naive = good[::step] # wrong: just throw samples away
spectrum = np.fft.rfft(good) # split the sound into its frequencies
freqs = np.fft.rfftfreq(len(good), d=1 / 44_100)
nyq = new_sr / 2 # the new Nyquist frequency: 4,410 Hz
gain = np.clip((nyq - freqs) / (0.2 * nyq), 0, 1) # keep up to 80% of Nyquist, fade out to zero at Nyquist
spectrum = spectrum * gain # the anti-aliasing filter
filtered = np.fft.irfft(spectrum, n=len(good))[::step] # rebuild the sound, then thin it out
save_wav("downsampled_naive.wav", naive, new_sr)
save_wav("downsampled_filtered.wav", filtered, new_sr)
fig, ax = plt.subplots(1, 2, figsize=(10, 3.4), sharey=True)
ax[0].specgram(naive, NFFT=256, Fs=new_sr, noverlap=192, cmap="magma", vmin=-110, vmax=-20)
ax[0].set_title("Every 5th sample: aliasing")
ax[1].specgram(filtered, NFFT=256, Fs=new_sr, noverlap=192, cmap="magma", vmin=-110, vmax=-20)
ax[1].set_title("Filtered first: the tone simply stops")
ax[0].set_ylabel("Frequency (Hz)")
for a in ax:
a.set_xlabel("Time (seconds)")
plt.tight_layout()
plt.show()With the filter, the frequencies that won't fit are lost, which is honest. Without it, they come back as tones that were never in the music. (Notice that the filter fades out gradually between 80% and 100% of the Nyquist frequency instead of cutting off abruptly. An abrupt cut-off "rings": it leaves a faint tone at the cut-off frequency running through the whole file. That's the same reason CDs leave a margin between 20,000 Hz and 22,050 Hz. Real audio software uses carefully designed filters, such as the one in scipy.signal.resample_poly, but the principle is the same.)
Aliasing in streaming data
Aliasing isn't only about sound. It happens whenever something that changes continuously is measured at intervals, and that includes the business side of music. Recall the simulated single from lesson 1.1, which gets about 12% more streams on Fridays and Saturdays. What if you only check its numbers once a week, or every six days?
rng = np.random.default_rng(7)
days = pd.date_range("2026-01-02", periods=182, freq="D") # starts on a Friday
lift = 1 + 0.12 * np.isin(days.day_of_week, [4, 5]) # Fridays and Saturdays are busier
daily = pd.Series(20_000 * lift * rng.normal(1, 0.01, len(days)), index=days)
every_7 = daily.iloc[::7] # check once a week
every_6 = daily.iloc[::6] # check every six days
print(f"True average per day: {daily.mean():,.0f}")
print(f"Average of the weekly checks: {every_7.mean():,.0f}")
fig, ax = plt.subplots(3, 1, figsize=(10, 6), sharex=True, sharey=True)
ax[0].plot(daily, linewidth=0.8)
ax[0].set_title("Every day: a weekly rhythm")
ax[1].plot(every_7, "o-", color="C1", markersize=4)
ax[1].set_title("Every 7th day (always a Friday): the rhythm vanishes and the level is too high")
ax[2].plot(every_6, "o-", color="C2", markersize=4)
ax[2].set_title("Every 6th day: a fake 42-day cycle")
plt.tight_layout()
plt.show()Checking once a week, always on a Friday, the weekly rhythm disappears completely. Worse, every check lands on a busy day, so the song looks about 8% more popular than it is. Checking every six days, the rhythm turns into a slow cycle that repeats every 42 days. Nothing in the song lasts 42 days. Each check lands one weekday earlier than the last, so it takes seven checks (42 days) to come back round to Friday.
It's the same folding rule as for sound. The weekly rhythm has a frequency of 1/7 per day, and sampling every six days means a rate of 1/6 per day, with a Nyquist frequency of 1/12 per day. The weekly rhythm is above that, so it folds down to |1/7 − 1/6| = 1/42 per day: one cycle every 42 days.
Many applied economists working with time-series data run into this problem. Much economic activity happens every day but is only recorded monthly or quarterly, and a cycle you see in sampled data may be partly an alias. How continuous processes look once they've been sampled is a core question of continuous-time econometrics.
Key ideas
- A digital recording is a set of samples of a continuous wave. The sample rate is how many per second.
- The Nyquist frequency is half the sample rate. Below it, sampling loses nothing (the sampling theorem).
- Frequencies above it alias: they fold back and pretend to be lower frequencies, and they can't be told apart from real ones afterwards.
- The cure is an anti-aliasing filter before sampling, or before reducing the sample rate.
- CDs use 44,100 Hz so the Nyquist frequency (22,050 Hz) sits above the limit of human hearing, with room for the filter.
- Aliasing affects any sampled data: checking streams on the same weekday hides the weekly rhythm and biases the average, and checking at the wrong interval invents cycles.
Try it yourself
- Use
alias()to find where a 9 Hz wave lands when sampled 8 times a second. Changef_trueto 9 in the first chart and check that your answer fits the dots. - Make the sweep run up to 20,000 Hz (
f1=20_000) and sample it at 8,000 Hz. How many times does the pitch turn round? Use the folding chart to predict it before you listen. - Downsample with
step = 10instead of 5. What is the new Nyquist frequency, and how does the naive version sound? - In the streams example, check every 3 days (
daily.iloc[::3]). Does the weekly rhythm survive? Work out the alias frequency to explain what you see.
Next lesson: Loading music data into pandas: audio, MIDI and streaming numbers. Open a WAV, a MIDI file and a CSV of streams, and turn each into a time series.
The course
Music as Data: Time Series with Python
1Music as a time series
2Seeing patterns
3Decomposition and stationarity
4Testing a time series
5Missing values
- 5.1Handling missing values in music data coming soon
6Autocorrelation and forecasting
- 6.1Autocorrelation: finding the beat coming soon
- 6.2Partial autocorrelation and lag plots coming soon
- 6.3How forecastable is a hit? coming soon
7Smoothing and Granger causality
- 7.1Smoothing: moving averages and loudness envelopes coming soon
- 7.2Granger causality: does social-media buzz predict streams? coming soon
8From time series to AI music
- 8.1From forecasting to generating: how AI music models predict what comes next coming soon