This exercise covers how sound is stored in a computer. A sound is a list of numbers, and if those numbers are taken too sparsely, high-frequency content gets corrupted.

How sound is stored in a computer

A computer can’t store a continuous vibration, so it records one number at fixed time intervals. Each number is a sample. The number of samples per second is the sampling rate (fs); this course always uses 44100 Hz. The value of each sample is its amplitude: the larger, the louder.

The grey line is the continuous sound, the blue dots are the recorded samples

The WAV files in the course are 16-bit, so each sample is an integer between -32768 and 32767, which gives \(2^{16} = 65536\) possible values.

wavread() divides each integer by 32768, turning it into a float in [-1, 1]. This is normalization. Files with different bit depths end up in the same range, and floating-point math avoids overflow and rounding loss. After normalization, the gap between two neighbouring levels is \(1/32768 \approx 0.0000305\).

fs, x = wavread('../sounds/piano.wav')

wavread returns the sampling rate fs and the sample array x. Python indexing starts at 0, and a slice x[a:b] includes a but not b, so it has b − a elements:

def read_audio(input_file, first_sample=50000, num_samples=10):
    fs, x = wavread(input_file)
    return x[first_sample:first_sample + num_samples]

Waveform and min/max values

plt.plot(x) puts the sample index on the x-axis. Divide by fs to get seconds:

t = np.arange(len(x)) / fs
plt.plot(t, x)
def min_max_audio(input_file):
    fs, x = wavread(input_file)
    return (float(x.min()), float(x.max()))

oboe-A4.wav gives (-0.835, 0.565), which is not symmetric. Possible causes are a DC offset or an asymmetric waveform.

  • A DC offset means the whole waveform is shifted up or down, so its mean is not 0;
  • An asymmetric waveform is still centred at 0, but its positive and negative halves have different shapes.

The waveform of oboe-A4.wav with its max, min and mean

The oboe’s x.mean() is about 0, so it’s the second case. Zoomed in, the downward spikes are clearly deeper than the upward ones. The oboe’s double reed opens and closes asymmetrically, so the waveform isn’t a pure sine wave.

If min and max are exactly -1.0 and 1.0, the recording was most likely too loud and the peaks were cut flat. This is clipping, and it sounds distorted. Normal peak normalization only makes the louder side reach 1, so both sides hitting ±1 at the same time is the suspicious sign.

Keeping one out of every M samples

The third number in a slice is the step:

def hop_samples(x, M):
    return x[::M]

np.arange(10) with M=2 gives [0, 2, 4, 6, 8]. As a formula:

$$ y[n] = x[nM] $$

The output length is len(x) / M rounded up, i.e. (len(x) + M - 1) // M, because index 0 is always selected. For example, 10 elements with M = 3 gives 0, 3, 6, 9, which is 4 elements.

Keeping one sample out of every M lowers the number of samples per second from fs to fs / M. This is downsampling.

Keep 1 out of every 3, then renumber

Downsampling and aliasing

def down_sample_audio(input_file, M):
    fs, x = wavread(input_file)
    y = hop_samples(x, M)
    fs_new = fs // M
    return (x, fs, y, fs_new)

Play it back with the new sampling rate, otherwise the speed is wrong:

ipd.Audio(data=y, rate=fs_new)

Nyquist frequency

To capture one full cycle you need at least two samples (one high, one low), so the highest frequency you can represent is half the sampling rate:

$$ f_{\text{Nyquist}} = \frac{fs}{2} $$
Sampling rateMax frequency
Original44100 Hz22050 Hz
M = 143150 Hz1575 Hz

Aliasing

After sampling, content above the Nyquist frequency shows up as a lower, wrong frequency. This is called aliasing. It’s the same thing as a fast-spinning wheel in a video that looks like it’s slowly turning backwards.

The aliased frequency is the distance from the original frequency to the nearest multiple of fs_new. With fs_new = 3150, a 3000 Hz tone becomes |3000 − 3150| = 150 Hz.

A 3000 Hz sine sampled at 3150 Hz: the samples trace out a 150 Hz wave

Between two samples, the original signal goes through almost one full cycle, just slightly short. Those small shortfalls add up, and the samples end up looking like a very slow wave.

So hop_samples only works for signals with nothing above fs / (2M), and most real sounds do have content there.

The two test sounds

vibraphone-C6sawtooth-440
Frequency contentBasically one, around 1050 HzEvery integer multiple of 440 Hz
Above 1575 HzAlmost nothingA lot
After downsamplingSounds the sameNew, strange tones appear

Spectra of the two test sounds; the shaded area is what aliases at M = 14

In the spectra, almost all of the vibraphone’s energy is around 1050 Hz, with only a few very weak peaks in the shaded area, while the sawtooth’s harmonics keep going and most of them land in the shaded area.

C6 ≈ 1046.5 Hz is obtained by starting at A4 = 440 Hz and multiplying by 2 per octave and by \(2^{1/12}\) per semitone. Counting peaks in 0.01 s of the waveform gives about 10.5, which matches.

The sawtooth contains every harmonic of its 440 Hz fundamental. 1575 / 440 ≈ 3.58, so only the first 3 are below 1575 Hz.

HarmonicFrequencyAfter downsampling
1440survives
2880survives
31320survives
417603150 − 1760 = 1390
522003150 − 2200 = 950
626403150 − 2640 = 510
730803150 − 3080 = 70
………

1390, 950, 510 and 70 are not multiples of 440, so they clash with the original pitch and sound harsh.

How to avoid it

Before downsampling, use a low-pass filter to remove everything above the new Nyquist frequency. Used this way, it’s called an anti-aliasing filter. The sound gets duller, but no false frequencies appear. scipy’s decimate filters first and then downsamples:

from scipy.signal import decimate
y_good = decimate(x, 14, ftype='fir')

Spectrum of the sawtooth after plain hopping vs. filtering first

This is the sawtooth’s spectrum after downsampling. With plain hopping, it’s not just the 70, 510, 950 and 1390 from the table: every higher harmonic folds down too, filling 0 to 1575 Hz with false peaks. With filtering first, only the three true harmonics at 440, 880 and 1320 remain.

Summary

  • A sound is a list of numbers sampled at fs, and wavread normalizes it to [-1, 1];
  • x[::M] is downsampling: the new sampling rate is fs / M, and the highest frequency it can represent is fs / (2M);
  • Anything above that aliases into a wrong, lower frequency. Low-pass filtering before downsampling prevents it.

Exercise source: E1-Python-and-sounds.ipynb