A computer stores sound as a list of numbers, one every 1/rate of a second, each rounded to a fixed number of bits. Two things can go wrong on the way in, and both are exact enough to compute: frequencies the rate cannot hold come back as other frequencies, and rounding adds noise. This lesson pairs with Coding Adventure: Sound (and the Fourier Transform) by Sebastian Lague, linked under Watch & read. The video covers sound waves, sample files, signal generation and the Nyquist rate. You build the small toolkit underneath: sampled sines, the frequency fold, a quantizer, a signal-to-noise meter, and a WAV file writer and reader.
A sampled sine is sin(2π · f · i / rate + φ) for i = 0, 1, 2, … Compute each sample from its index. Adding a small phase step on every iteration works for a second or two, then rounding errors pile up and a long tone slowly goes out of tune. The count is round(seconds · rate).
The picture is the whole story of aliasing. At rate 10 the sample times are i/10, so a frequency of f Hz and one of f - 10 Hz differ by a whole number of turns at every sample, and a cosine cannot tell them apart. The same holds for f and -f. Every frequency therefore folds into the band 0 to rate/2, the Nyquist frequency. To fold f: take |f| modulo the rate, and if the result is above rate/2, replace it by rate minus it. Skipping the modulo is a classic mistake. It folds 8 Hz correctly at rate 10, then returns -13 for 23 Hz.
import numpy as np
i = np.arange(10)
loud = np.cos(2 * np.pi * 8 * i / 10)
slow = np.cos(2 * np.pi * 2 * i / 10)
print(np.allclose(loud, slow), round(float(loud[1]), 4))
f = abs(23) % 10
print(f, 10 - f if f > 5 else f)Folding works for a cosine. A sine of the aliased frequency can flip sign, so the lesson tests with phase π/2, which turns a sine into a cosine.
Quantization is the second step. A signed b-bit quantizer has 2ᵇ levels spaced 1/2ᵇ⁻¹ apart: scale by 2ᵇ⁻¹, round to the nearest integer, clip, and scale back. Because the integers run from -2ᵇ⁻¹ to 2ᵇ⁻¹ - 1, the top level is one step below 1.0, and +1.0 itself clips. With 3 bits the steps are 0.25 apart: 0.3 becomes 0.25, and 0.9 becomes 0.75, not 1.0. Forgetting the clip lets one level too many through.
The error of rounding is at most half a step, so it shrinks by half for every extra bit. In decibels, 10 · log10(Σx² / Σ(x - y)²) is the signal-to-noise ratio, and halving the error amplitude adds about 6 dB. Measure it instead of trusting it:
import numpy as np
x = 0.9 * np.sin(2 * np.pi * 440 * np.arange(48000) / 48000)
for bits in (4, 8, 12, 16):
q = np.round(x * 2 ** (bits - 1)) / 2 ** (bits - 1)
print(bits, round(10 * np.log10(np.sum(x ** 2) / np.sum((x - q) ** 2)), 1))Every four extra bits add about 24 dB, close to 6 dB per bit. The exact figure depends on the signal, so the hidden tests allow half a decibel.
A WAV file is a header followed by the samples. The 44 bytes hold the tags RIFF, WAVE, fmt and data, the sizes of the file and of the data, the format code 1 for PCM, the channel count, the rate, bytes per second, bytes per frame and bits per sample. Everything is little-endian, which struct writes with a leading "<". A reader should walk the chunks by size rather than assume the data starts at byte 44, because real files often carry extra chunks.
import numpy as np
x = np.array([1.0, -1.0])
for scale in (32767, 32768):
print(scale, (x * scale).round().astype(np.int64).astype("<i2").tolist())Scaling by 32768 looks natural, since that is the size of the int16 range, but +1.0 becomes 32768, which wraps to -32768 and turns the loudest peak into the most negative sample. The fix is 32767 and a clip. The reader divides by 32768, as most audio software does, so a round trip returns values within about 3·10⁻⁵ of the original.
fade and mix are the small editing tools. A fade multiplies the first and last n samples by i/n so a sound starts and ends at exactly zero, avoiding a click. Mixing adds gain-weighted tracks, padding shorter ones with silence, and does not clip: leave that decision to the final quantization.
How is this verified? Python's own wave module reads your file and writes files your reader must parse. A brute-force search over every quantizer level checks the rounding. A sampled cosine of f and of its alias must agree sample for sample. An exact rational-arithmetic sine checks drift. What this does not show is how a signal sounds, or how to find out which frequencies a recording contains. The next lesson, on the Fourier transform, takes up the second question.