Audio Basics: From Sound Waves to Spectrograms
How a microphone signal becomes numbers (sample rate, bit depth), why the Fourier transform matters, and how spectrograms and mel spectrograms became the standard input for audio AI.
Every audio AI system — voice assistants, auto-captioning, music generators, call-center analytics — starts from the same raw material: a long list of numbers measured from air pressure. Before a model can recognise a word or generate a melody, we have to decide how often to measure (sample rate), how precisely (bit depth), and how to represent the result so that patterns become easy to learn. This lesson builds that foundation, from the Waveform to the Mel spectrogram that most speech models actually see.
1. Sampling: sample rate and the Nyquist limit
Sound is a continuous pressure wave. An analog-to-digital converter measures it at regular intervals; the number of measurements per second is the Sample rate (in hertz, Hz). The Nyquist–Shannon sampling theorem[1] says a signal can be perfectly reconstructed only if it contains no frequencies above half the sample rate — the Nyquist frequency. Frequencies above it do not disappear: they fold back and masquerade as lower frequencies. This is called aliasing, and it is why converters put a low-pass (anti-aliasing) filter before sampling.
- f_Nyquist
- Nyquist frequency: the highest frequency that can be captured without aliasing (Hz)
- f_s
- sample rate: samples per second, e.g. 16,000 Hz for speech, 44,100 Hz for music
- f_alias
- the false frequency you actually hear/measure after sampling a too-high tone
- f
- the true frequency of the tone in the analog signal
- k
- an integer (0, 1, 2, …) chosen so that k·f_s is the multiple of the sample rate closest to f
- | f − k·f_s |
- absolute value |·|: the distance, always positive
▸Worked example
| Sample rate | Nyquist | Typical use |
|---|---|---|
| 8 kHz | 4 kHz | Classic telephone audio (narrowband) |
| 16 kHz | 8 kHz | Most speech recognition models (wav2vec 2.0, Whisper) |
| 22.05 / 24 kHz | 11–12 kHz | Many TTS models and neural codecs |
| 44.1 kHz | 22.05 kHz | CD audio; covers human hearing (~20 kHz) |
| 48 kHz | 24 kHz | Video, film, professional audio |
2. Quantization: bit depth
Each sample is stored as an integer with a fixed number of bits — the Bit depth. With b bits there are 2ᵇ levels, so rounding introduces small errors (quantization noise). Each extra bit adds about 6 dB of dynamic range: 16-bit audio has ~96 dB, enough for CD quality; 24-bit (~144 dB) gives studios headroom. Inside ML pipelines, audio is almost always converted to 32-bit floats in the range [−1, 1], so bit depth mostly matters when recording and storing.
- levels
- number of distinct amplitude values a sample can take
- 2ᵇ
- 2 to the power b: each bit doubles the count
- b
- bit depth: bits per sample (8, 16, 24)
- dynamic range
- ratio between the largest signal and the quantization noise, in decibels
- dB
- decibel: a logarithmic scale; +6 dB ≈ twice the amplitude
- f_s
- sample rate in Hz (samples per second)
- channels
- 1 = mono, 2 = stereo
- seconds
- duration of the recording
- / 8
- 8 bits = 1 byte
▸Worked example
3. From time to frequency: the Fourier transform
A waveform tells you *when* the pressure changed, but our ears (and most audio models) care about *which frequencies* are present. The Fourier transform rewrites a signal as a sum of sine waves; the Discrete Fourier Transform (DFT) does this for N samples, and the Fast Fourier Transform (FFT) (Fast Fourier Transform) computes it in O(N log N) instead of O(N²). The output has N/2 + 1 useful frequency bins spaced f_s / N apart, each with a magnitude (how loud) and a phase.
- X[k]
- the k-th frequency bin: a complex number whose size is the strength of frequency k·Δf
- Σₙ₌₀ᴺ⁻¹
- sum over all samples n = 0, 1, …, N − 1 in the window
- x[n]
- the n-th audio sample in the window
- e^(−2πi·k·n/N)
- a complex sinusoid (cos − i·sin) that makes k full turns over the window
- i
- the imaginary unit, i² = −1; it lets one number hold both amplitude and phase
- N
- window length in samples (e.g. 400 = 25 ms at 16 kHz)
- Δf
- frequency resolution: spacing between bins in Hz
- Δt
- window duration in seconds
- f_s
- sample rate in Hz
▸Worked example
4. Spectrograms: the STFT
Speech and music change over time, so one FFT over the whole file is useless. The Short-Time Fourier Transform (STFT) slides a short window (e.g. 25 ms) along the signal with a step called the hop length (e.g. 10 ms), multiplies each frame by a smooth window function (usually Hann, to avoid spectral leakage from hard edges), and runs an FFT on each frame. Stacking the magnitudes column by column gives a Spectrogram: time on the x-axis, frequency on the y-axis, loudness as colour. Magnitudes are usually converted to decibels (log scale) because loudness perception is roughly logarithmic.
Mel spectrograms: frequencies the way ears hear them
Humans distinguish 100 Hz from 200 Hz easily, but 10,000 Hz from 10,100 Hz hardly at all. The mel scale warps frequency to match this: roughly linear below 1 kHz, logarithmic above. A Mel spectrogram applies a bank of triangular filters (typically 64–128 *mel bins*) to the STFT power, then takes the log. The result is compact (80 rows instead of 201 or 1025) and perceptually meaningful — it is the input to Whisper, Tacotron 2 and most modern speech systems[2][3]. Older systems went one step further to MFCCs (a discrete cosine transform of the log-mel), which are still useful for small classical models.
- m
- the pitch on the mel scale (unit: mel)
- f
- frequency in Hz
- log₁₀
- base-10 logarithm: log₁₀(10) = 1, log₁₀(100) = 2
- 2595
- constant chosen so that 1000 Hz ≈ 1000 mel
- 700
- corner frequency (Hz) where the scale turns from roughly linear to logarithmic
▸Worked example
- Aliasing: set the sample rate to 8 kHz and raise one oscillator above 4 kHz. Watch its line in the spectrogram *fold back down* instead of going up — then switch to 44.1 kHz and see it move to the correct place.
- Time vs frequency trade-off: put two oscillators close together (e.g. 440 Hz and 470 Hz) and turn on the chirp. With window size 128 the two tones blur into one band but the chirp is sharp in time; with 2048 the tones separate cleanly but the chirp smears.
- Noise: raise the noise level and notice that white noise fills *all* frequencies evenly, while the sines stay as thin horizontal lines.
- Mel axis: toggle linear → mel. Low frequencies get stretched (more rows), high frequencies get squeezed — the same compression your ears apply.
- Microphone: record 2 seconds of yourself saying “aaa” then “sss”. Vowels show stacked horizontal harmonics; “s” is a noisy smear above ~4 kHz.
The knobs
- What it is
- Samples per second. Sets the highest representable frequency (f_s / 2) and how many numbers the model must process per second.
- ↑ If you increase it
- Captures higher frequencies (cymbals, sibilants), but more data per second: longer sequences, more memory and compute. Above ~24 kHz there is little benefit for speech.
- ↓ If you decrease it
- Cheaper and faster, but high frequencies are lost; without a low-pass filter they alias into fake lower tones. Speech at 8 kHz still sounds intelligible but muffled (“phone quality”).
- Typical values
- 16 kHz for ASR; 22.05–24 kHz for TTS; 32–48 kHz for music. Always resample to the rate the pretrained model expects.
- What it is
- Bits per sample in the stored/recorded signal; sets the number of amplitude levels (2ᵇ) and the noise floor.
- ↑ If you increase it
- Lower quantization noise, more dynamic range (~6 dB per bit), larger files. Beyond 16-bit, rarely audible in playback.
- ↓ If you decrease it
- Smaller files, but audible hiss/graininess; 8-bit audio sounds noticeably noisy on quiet passages.
- Typical values
- 16-bit for datasets and delivery; 24-bit for recording; float32 inside models.
- What it is
- Number of samples in each STFT frame. Controls the time–frequency trade-off: Δf = f_s / N, Δt = N / f_s.
- ↑ If you increase it
- Finer frequency resolution (separates close pitches, good for music), but transients and fast changes smear in time.
- ↓ If you decrease it
- Sharper timing (drum hits, consonant onsets), but nearby frequencies merge into broad bands.
- Typical values
- Speech: 25 ms windows (400 samples at 16 kHz, often zero-padded to n_fft = 512). Music: 2048 at 44.1 kHz (~46 ms).
- What it is
- Step (in samples) between consecutive STFT frames; sets the frame rate of the spectrogram (f_s / hop).
- ↑ If you increase it
- Fewer frames per second → shorter sequences and cheaper models, but fast events may fall between frames.
- ↓ If you decrease it
- Smoother, more detailed time axis, but more frames (more compute) and highly redundant neighbouring columns.
- Typical values
- 10 ms for speech (160 samples at 16 kHz) = 100 frames/s; window/4 for music.
- What it is
- Number of triangular mel filters, i.e. rows of the mel spectrogram.
- ↑ If you increase it
- More spectral detail (useful for music, high-fidelity vocoders), bigger input; with small n_fft some filters become empty.
- ↓ If you decrease it
- Compact, smooth input that generalises well for speech, but pitch details and timbre nuances are lost.
- Typical values
- 80 (Whisper up to large-v2, Tacotron 2), 128 (Whisper large-v3, music models), 40–64 for keyword spotting.
In code: librosa and torchaudio
import numpy as np
import librosa
# Load and resample to 16 kHz mono float32 in [-1, 1]
y, sr = librosa.load("speech.wav", sr=16000, mono=True)
# Linear STFT spectrogram: 25 ms Hann window, 10 ms hop
S = np.abs(librosa.stft(y, n_fft=512, win_length=400, hop_length=160, window="hann"))
S_db = librosa.amplitude_to_db(S, ref=np.max) # shape: (257, frames)
# Log-mel spectrogram (what most speech models consume)
mel = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=512, win_length=400,
hop_length=160, n_mels=80)
log_mel = librosa.power_to_db(mel, ref=np.max) # shape: (80, frames)
print(S_db.shape, log_mel.shape) # ~100 frames per second of audioimport torch, torchaudio
wav, sr = torchaudio.load("speech.wav") # (channels, samples)
wav = torchaudio.functional.resample(wav, sr, 16000).mean(0, keepdim=True)
to_mel = torchaudio.transforms.MelSpectrogram(
sample_rate=16000, n_fft=400, hop_length=160, n_mels=80)
log_mel = torch.log(to_mel(wav) + 1e-6) # (1, 80, frames)▸Go deeper: windows, leakage and the uncertainty principle
The FFT assumes each frame repeats forever. If a sine wave does not complete a whole number of cycles inside the frame, the hard cut creates a discontinuity, and its energy “leaks” into neighbouring bins. Tapering windows (Hann, Hamming, Blackman) fade the frame edges to zero, trading a slightly wider main peak for much lower leakage. Overlapping frames (hop < window) compensate for the faded edges.
The time–frequency trade-off is fundamental (the Gabor limit, a cousin of Heisenberg's uncertainty principle): Δt · Δf has a lower bound. That is why researchers also use multi-resolution STFT losses (several window sizes at once) when training vocoders, and why some models skip spectrograms entirely and learn their own filterbank from the raw waveform (wav2vec 2.0, EnCodec).
Quiz
References
- [1]
- [2]librosa documentation — feature.melspectrogramDocsMcFee et al.librosa.orgSTFT and mel spectrogram parameters.
- [3]Robust Speech Recognition via Large-Scale Weak Supervision (Whisper)PaperRadford et al.2022arxiv.org80-channel log-mel input, 25 ms windows, 10 ms stride.
- [4]torchaudio documentationDocspytorch.org