AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
♪Audio & Speech AI
  1. Audio Basics: From Sound Waves to Spectrograms
  2. Speech Recognition: CTC, wav2vec 2.0 and Whisper
  3. Speech Synthesis: From Text to a Natural Voice
  4. Music & Audio Generation: Codecs, Tokens and Diffusion
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Audio & Speech AI

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.

Beginner~22 min·4 references
Key terms
WaveformSample rateBit depthFast Fourier Transform (FFT)SpectrogramMel spectrogram

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.

≈
Analogy: a flip-book of air pressure
Think of digital audio as a flip-book. Each page is one sample: a snapshot of how far the microphone membrane is pushed at one instant. The sample rate is how many pages per second; the bit depth is how finely each page can draw the position (a ruler with 65,536 tick marks for 16-bit). Too few pages and fast movements (high pitches) get garbled; too coarse a ruler and quiet details drown in rounding noise.

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 = f_s / 2 f_alias = | f − k·f_s | (nearest multiple k)
Example: a 5 kHz tone sampled at 8 kHz (Nyquist = 4 kHz) shows up as |5 − 8| = 3 kHz.
In words: The highest frequency a sampled signal can represent is half the sample rate. Anything above it does not disappear: it folds back and pretends to be a lower frequency (aliasing). That is why audio is low-pass filtered before sampling.
Symbols(hover a symbol in the formula)
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
Speech at f_s = 16,000 Hz: f_Nyquist = 16,000 / 2 = 8,000 Hz A 9,000 Hz hiss (above Nyquist), nearest multiple k = 1: f_alias = |9,000 − 1 · 16,000| = 7,000 Hz → it is recorded as a 7 kHz tone that was never there. A 3,000 Hz tone (below Nyquist): k = 0 → |3,000 − 0| = 3,000 Hz, unchanged.
Sample rateNyquistTypical use
8 kHz4 kHzClassic telephone audio (narrowband)
16 kHz8 kHzMost speech recognition models (wav2vec 2.0, Whisper)
22.05 / 24 kHz11–12 kHzMany TTS models and neural codecs
44.1 kHz22.05 kHzCD audio; covers human hearing (~20 kHz)
48 kHz24 kHzVideo, 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 = 2ᵇ dynamic range ≈ 6.02·b + 1.76 dB size = f_s × b × channels × seconds / 8 bytes
One minute of 16-bit mono at 16 kHz: 16000 × 16 × 60 / 8 ≈ 1.9 MB. At 44.1 kHz stereo: ≈ 10.6 MB.
In words: Each extra bit doubles the number of amplitude levels and adds about 6 dB of dynamic range (the gap between the loudest sound and the quantization noise floor). File size grows linearly with sample rate, bit depth, channels and duration; dividing by 8 converts bits to bytes.
Symbols(hover a symbol in the formula)
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
b = 16: levels = 2¹⁶ = 65,536 dynamic range ≈ 6.02 · 16 + 1.76 = 98.08 dB b = 8: levels = 2⁸ = 256 dynamic range ≈ 6.02 · 8 + 1.76 = 49.92 dB Size, 1 min, 16 kHz, 16-bit mono: 16,000 × 16 × 1 × 60 / 8 = 1,920,000 bytes ≈ 1.9 MB Size, 1 min, 44.1 kHz, 16-bit stereo: 44,100 × 16 × 2 × 60 / 8 = 10,584,000 bytes ≈ 10.6 MB

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] = Σₙ₌₀ᴺ⁻¹ x[n] · e^(−2πi·k·n/N) Δf = f_s / N Δt = N / f_s
Frequency resolution Δf and window duration Δt are inversely related: you cannot have both very fine at once.
In words: The discrete Fourier transform asks, for each frequency bin k: “how much does the signal look like a wave that completes k cycles in this window?” It multiplies the samples by a rotating complex wave and adds them up; a large |X[k]| means strong energy at that frequency. The bins are Δf apart, and a window of N samples lasts Δt, so finer frequency detail needs a longer window.
Symbols(hover a symbol in the formula)
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
Tiny DFT, N = 4, x = [1, 0, −1, 0] (a cosine doing 1 cycle per window): X[0] = 1 + 0 − 1 + 0 = 0 (no DC offset) X[1] = 1·1 + (−1)·e^(−iπ) = 1 + 1 = 2 (strong: 1 cycle per window) X[2] = 1·1 + (−1)·e^(−2πi) = 1 − 1 = 0 X[3] = 2 (mirror image of X[1] for real signals) Window sizes at f_s = 16,000 Hz: N = 400 → Δf = 16,000 / 400 = 40 Hz, Δt = 400 / 16,000 = 0.025 s N = 512 → Δf = 31.25 Hz, Δt = 0.032 s

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 = 2595 · log₁₀(1 + f / 700)
A common (HTK-style) Hz → mel conversion. 1000 Hz ≈ 1000 mel; 8000 Hz ≈ 2840 mel.
In words: The mel scale bends the frequency axis to match human hearing: roughly linear below ~1 kHz, logarithmic above it. Equal steps in mel sound like equal steps in pitch, which is why mel filterbanks spend more resolution on low frequencies, where speech information lives.
Symbols(hover a symbol in the formula)
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
f = 1000 Hz: 1 + 1000/700 = 2.4286 → log₁₀ = 0.3854 → m = 2595 · 0.3854 ≈ 1000 mel f = 4000 Hz: 1 + 4000/700 = 6.714 → log₁₀ = 0.8270 → m ≈ 2146 mel f = 8000 Hz: 1 + 8000/700 = 12.43 → log₁₀ = 1.0944 → m ≈ 2840 mel → going 1 → 4 kHz adds ~1146 mel, but 4 → 8 kHz adds only ~694: high frequencies get squeezed.
Loading interactive…
A real FFT running in your browser: build a signal from sine waves, noise and a chirp, then inspect its waveform and STFT spectrogram.
  • 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

knobsample_rate (f_s)
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.
knobbit_depth
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.
knobn_fft / window size
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).
knobhop_length
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.
knobn_mels
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

python
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 audio
librosa defaults to sr=22050 if you omit sr — a classic silent bug when a model expects 16 kHz.
python
import 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)
torchaudio runs on GPU and inside the model graph, handy for on-the-fly feature extraction during training[4].
!
Common pitfalls
Sample-rate mismatch is the #1 bug: feeding 44.1 kHz audio to a 16 kHz model makes speech sound slowed-down to the model and accuracy collapses — always resample. Clipping (samples stuck at ±1) adds harsh harmonics that no model can undo. Stereo vs mono: average channels unless the model expects stereo. Feature mismatch: a model trained on log-mel with n_mels = 80 and hop = 160 will silently misbehave on features computed with different settings — reuse the model's own feature extractor. Finally, the magnitude spectrogram throws away phase, which is why generating audio from a spectrogram needs a Vocoder.
▸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

1.
You sample audio at 16 kHz. What is the highest frequency you can represent without aliasing?
2.
What happens to a 6 kHz tone if you sample it at 8 kHz without an anti-aliasing filter?
3.
You increase the STFT window size from 256 to 2048 samples. What do you expect?
4.
Why do most speech models use a log-mel spectrogram rather than raw STFT bins?
5.
A pretrained ASR model expects 16 kHz input, but you pass a 44.1 kHz file without resampling. What is the most likely result?
Score: 0/5

References

  1. [1]
    Communication in the Presence of Noise
    PaperShannon1949doi.org
    The sampling theorem.
  2. [2]
    librosa documentation — feature.melspectrogram
    DocsMcFee et al.librosa.org
    STFT and mel spectrogram parameters.
  3. [3]
    Robust Speech Recognition via Large-Scale Weak Supervision (Whisper)
    PaperRadford et al.2022arxiv.org
    80-channel log-mel input, 25 ms windows, 10 ms stride.
  4. [4]
    torchaudio documentation
    Docspytorch.org
← Previous
Stable Diffusion in Practice
Next →
Speech Recognition: CTC, wav2vec 2.0 and Whisper