Speech & Audio
Recognizing and synthesizing sound.
One second of speech is 16,000 numbers and about three words. Recognizing speech means squeezing a long, noisy signal into a short sequence of symbols without knowing which samples belong to which word; synthesizing it means inventing tens of thousands of samples per second that a listener accepts as a voice. This lesson follows both directions, from the sampling theorem to models that generate speech one token at a time.
What you’ll learn
- State the sampling theorem, explain aliasing, and compute where an undersampled frequency appears.
- Compute a log-mel spectrogram from the short-time Fourier transform, and explain the mel scale and MFCCs.
- Explain the alignment problem in speech recognition and how CTC, attention decoders and transducers solve it; compute word error rate.
- Describe neural speech synthesis: WaveNet's dilated causal convolutions, mel-spectrogram models with neural vocoders, and codec language models.
Sound as numbers: sampling and Nyquist
Sound is air pressure varying in time. A microphone turns it into a voltage , which is digitized by sampling at a rate (samples per second) and quantizing each sample, typically to 16 bits. Telephone speech uses 8 kHz, speech recognition usually 16 kHz, speech synthesis 22.05–24 kHz, and CD audio 44.1 kHz.
Even at 16 kHz, a sentence is a sequence of tens of thousands of numbers, while its transcript has a few dozen characters. Speech recognition and synthesis are sequence problems with very different lengths on the two sides. How fast must you sample to lose nothing?
Sampling multiplies by a train of impulses spaced apart. In frequency, that copies the spectrum at every multiple of :
If the copies do not overlap, so an ideal low-pass filter with cutoff keeps exactly the original copy. Its impulse response is a sinc, which gives the interpolation formula:
If the copies overlap: a component at produces exactly the same samples as one at . This aliasing cannot be undone afterwards, which is why audio is low-pass filtered before it is sampled.
A 10 kHz tone is sampled at 16 kHz with no anti-aliasing filter. At what frequency, in kHz, does it appear in the samples?
Show the answer
6 kHz
The Nyquist frequency is 8 kHz, and 10 kHz folds back to kHz: the samples of the 10 kHz tone are identical to those of a 6 kHz tone. Nothing downstream can tell them apart.
Spectrograms, the mel scale and MFCCs
What a sound means lies in how its frequency content changes over time. Vowels are shaped by resonances of the vocal tract (formants), the pitch of a voice by how fast the vocal folds vibrate, and many consonants by bursts and noise. The short-time Fourier transform (STFT) cuts the signal into overlapping frames, multiplies each by a window , and Fourier-transforms it; the squared magnitude is a spectrogram:
Hearing resolves low frequencies finely and high ones coarsely. The mel scale (Stevens, Volkmann & Newman, 1937) is roughly linear below 1 kHz and logarithmic above; a common formula is , which maps 1,000 Hz to 1,000 mel. A mel filterbank sums the power spectrum under 40 to 128 triangular filters equally spaced in mel. Taking the logarithm gives the log-mel spectrogram: the standard input of modern recognizers (Whisper uses 80 channels) and the standard output of synthesis models.
MFCCs (mel-frequency cepstral coefficients; Davis & Mermelstein, 1980) take one more step: a discrete cosine transform of the log-mel energies, keeping the first dozen or so coefficients. The log turns the product of excitation (pitch) and vocal-tract filter into a sum, and the low DCT coefficients keep the smooth spectral envelope, which identifies the phone, while discarding the fine harmonic structure of pitch. The DCT also decorrelates the features, which suited the diagonal-covariance Gaussians of classical recognizers. Deep networks now usually take log-mel spectrograms, or even raw waveforms.
import numpy as np
def log_mel(x, sr=16000, n_fft=400, hop=160, n_mels=80):
frames = np.lib.stride_tricks.sliding_window_view(x, n_fft)[::hop]
power = np.abs(np.fft.rfft(frames * np.hanning(n_fft), axis=1)) ** 2 # (T, 201)
mel = lambda f: 2595 * np.log10(1 + f / 700)
inv = lambda m: 700 * (10 ** (m / 2595) - 1)
edges = inv(np.linspace(0, mel(sr / 2), n_mels + 2)) # filter corners in Hz
bins = np.fft.rfftfreq(n_fft, 1 / sr) # FFT bin frequencies
fb = np.zeros((n_mels, len(bins)))
for i in range(n_mels): # triangular filters
lo, mid, hi = edges[i], edges[i + 1], edges[i + 2]
fb[i] = np.clip(np.minimum((bins - lo) / (mid - lo), (hi - bins) / (hi - mid)), 0, None)
return np.log(power @ fb.T + 1e-10) # (T, n_mels) log-mel spectrogramFrame, window, FFT, mel filterbank, log. Libraries differ in details (mel formula, filter normalization, log base), so features from one toolkit rarely match another's exactly.
With , the band from 0 to 8 kHz spans about 2,840 mel. What percentage of that mel range does the upper half of the band, 4–8 kHz, occupy?
Show the answer
24 %
and , so 4–8 kHz covers of the mel axis. Half the hertz get only a quarter of the filters, matching how coarsely hearing resolves high frequencies.
Recognizing speech: from HMMs to CTC
Speech recognition maps acoustic frames , about 100 per second, to a word or character sequence of length . The classical formulation, developed by Jelinek and colleagues at IBM in the 1970s, is Bayes' decision rule with a noisy-channel model:
For decades the acoustic model was a hidden Markov model: each phone a three-state left-to-right HMM, context-dependent triphones with tied states, Gaussian-mixture emissions over MFCCs, all trained by Baum–Welch. Decoding ran Viterbi search over a weighted finite-state transducer composing the HMMs, a pronunciation lexicon and an n-gram language model (Markov Chains, HMMs & Filters, HMM Algorithms). Around 2010–2012 deep networks replaced the Gaussian mixtures: hybrid DNN–HMM systems predict the HMM state posteriors and divide by the state priors to obtain scaled likelihoods, with large error reductions (Hinton et al., 2012).
End-to-end models drop the HMM, but they face the alignment problem: the training data say which words were spoken, not which frames belong to which symbol. Connectionist temporal classification (CTC; Graves et al., 2006) sums over all alignments. At every frame the network outputs a distribution over the alphabet plus a blank , and a frame-level path is read out by the collapse map : merge repeated symbols, then delete blanks.
Which frame-level path collapses to the label sequence under CTC?
Show the answer
B.
Repeats merge first, so two consecutive 's become one; only a blank between them keeps both. has no adjacent repeats, and deleting the blank leaves . This is why a word like "hello" needs at least frames.
CTC-GREEDY-DECODE(frame posteriors y[1..T, symbols])
best ← [argmax_k y[t, k] for t = 1..T] // most likely symbol at each frame
out ← [ ]; prev ← none
for s in best:
if s ≠ prev and s ≠ blank: append s to out
prev ← s
return outBest-path decoding is fast but approximate: the most probable labeling sums over many paths, and a prefix beam search with an external language model does better. The language model matters more for CTC than for other designs because of the independence assumption.
Attention, transducers and weak supervision
Two other end-to-end designs drop CTC's independence assumption. Attention encoder–decoders such as Listen, Attend and Spell (Chan et al., 2016) encode the audio (LAS's pyramidal BiLSTM shortens the time axis 8-fold) and emit characters autoregressively, attending over the encoder states as in machine translation (Sequence-to-Sequence Models): . They are accurate but need the whole utterance before decoding, and on long inputs attention can loop or skip.
Transducers (RNN-T; Graves, 2012) keep CTC's monotonic alignment and add a prediction network over the labels emitted so far. At each point of a lattice, a joint network combines encoder frame with a summary of the first labels and outputs either the next label (moving to ) or a blank (moving to frame ). Because the output never waits for future audio beyond the current frame, transducers suit streaming recognition and are widely used on devices.
| Property | CTC | Attention encoder–decoder | Transducer (RNN-T) |
|---|---|---|---|
| Outputs depend on earlier outputs? | no: conditionally independent per frame | yes | yes |
| Alignment | monotonic, summed over | soft attention, learned | monotonic, summed over |
| Streaming | yes | not natively | yes |
| Language knowledge | an external language model helps a lot | implicit in the decoder | implicit in the prediction network |
Scale changed the picture again. Whisper (Radford et al., 2023) trained an encoder–decoder transformer on 680,000 hours of audio paired with transcripts collected from the internet: "weak" supervision, noisy but vast and multilingual. The input is 30 seconds of 80-channel log-mel spectrogram, and the decoder emits text tokens after special tokens that select the language, the task (transcription, or translation into English) and whether to predict timestamps. Evaluated zero-shot, with no training on any benchmark's own training set, it was far more robust across datasets than models fine-tuned on a single benchmark.
Self-supervised pretraining attacks the same bottleneck from the other side: wav2vec 2.0 (Baevski et al., 2020) learned representations from unlabeled audio with a contrastive objective and, fine-tuned with CTC, yielded usable recognizers from as little as ten minutes of transcribed speech.
Making sound: vocoders, codecs and token models
Speech synthesis (text-to-speech, TTS) runs the pipeline backward: normalize the text ("Dr." becomes "doctor", "1999" becomes "nineteen ninety-nine"), convert it to phonemes, predict acoustic features, usually a mel spectrogram, and finally generate the waveform. That last stage, the vocoder, must invent the phase that the spectrogram threw away.
WaveNet (van den Oord et al., 2016) modeled the waveform itself, one sample at a time: , conditioned on linguistic features . Each sample is companded with the μ-law and quantized to 256 levels, so every step is a 256-way softmax. To see far into the past cheaply, WaveNet stacks dilated causal convolutions with kernel size 2 and dilations 1, 2, 4, …, 512, so one block of ten layers sees 1,024 samples (the receptive-field formula of Convolutional Networks in Depth). Training is parallel, but sampling is sequential: 16,000 network passes for one second of 16 kHz audio.
Tacotron 2 (Shen et al., 2018) split the job: an attention sequence-to-sequence model predicts 80-channel mel spectrograms from characters, and a WaveNet vocoder turns them into audio. In the authors' listening tests its naturalness came close to that of recorded speech. GAN vocoders such as HiFi-GAN (Kong, Kim & Bae, 2020) then generated waveforms in parallel, much faster than real time, judged by discriminators that view the audio at several periods and time scales (Generative Models).
Neural audio codecs compress audio into discrete tokens. SoundStream (Zeghidour et al., 2022) and EnCodec (Défossez et al., 2023) pair a convolutional encoder and decoder with residual vector quantization: one codebook quantizes each frame's embedding, the next quantizes what the first missed, and so on. EnCodec's 24 kHz model produces 75 frames per second, each coded by up to 32 codebooks of 1,024 entries. Once audio is tokens, a language model can generate it. VALL-E (Wang et al., 2023) treats TTS as language modeling over EnCodec tokens: given phonemes and a 3-second recording of an unseen speaker, it continues in that voice. Its authors flagged the risk of misuse, such as spoofing voice identification or impersonating a speaker.
Music adds long-range structure, such as themes that return minutes later, and many simultaneous voices. Symbolic models generate notes as event sequences; audio models generate sound directly, often with the same codec tokens or with latent diffusion. Evaluating them is hard: there is no reference transcript, and embedding-based scores such as the Fréchet Audio Distance inherit FID's caveats.
Key takeaways
- Audio sampled at loses nothing; above the Nyquist frequency , frequencies alias, so audio is filtered before sampling. Speech is long: 16,000 numbers per second at 16 kHz.
- The STFT (about 25 ms windows every 10 ms) gives a spectrogram; mel filters and a logarithm give the log-mel spectrogram, and a DCT of it gives MFCCs, separating the vocal-tract envelope from pitch.
- Classical recognizers combined HMM acoustic models with -gram language models. End-to-end models solve alignment by summing over paths with a blank (CTC), by attention, or with transducers; Whisper scaled weak supervision. WER can exceed 100%.
- Synthesis goes text to mel spectrogram to waveform. WaveNet's dilated causal convolutions see 1,024 samples per block but sample one value at a time; GAN vocoders generate in parallel; neural codecs turn audio into tokens that language models such as VALL-E generate.
- Recognition errors fall unevenly across speakers, and voice cloning raises questions of consent and fraud.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why do recognizers take the logarithm of mel filterbank energies rather than using the energies directly?
- The FFT only works on logarithms
- To make all features positive
- It compresses the huge dynamic range, roughly as loudness perception does, and turns multiplicative effects such as source times filter, or a microphone's response, into additive ones
- It removes the need for a window function
Show the answer
C. It compresses the huge dynamic range, roughly as loudness perception does, and turns multiplicative effects such as source times filter, or a microphone's response, into additive ones
Energies span many orders of magnitude, and a fixed linear filter (vocal tract, microphone, room) multiplies the spectrum. In the log domain these become additive offsets, which the DCT of MFCCs and simple per-utterance mean subtraction can separate or remove.
Which property of CTC makes an external language model especially valuable when decoding it?
- It needs at least as many frames as output symbols
- Given the audio, its outputs at different frames are conditionally independent, so it never conditions on the symbols it has already emitted
- It cannot represent repeated letters
- It is trained without transcripts
Show the answer
B. Given the audio, its outputs at different frames are conditionally independent, so it never conditions on the symbols it has already emitted
is a sum of products of per-frame probabilities, so the model cannot learn spelling or word-sequence regularities except through the encoder's view of the audio. An -gram or neural language model added during beam search supplies them.
Reference: "the cat sat on the mat". Hypothesis: "a cat sat on the the mat". What is the word error rate?
Show the answer
C.
The best alignment has one substitution (the → a) and one insertion (the extra "the"): . The denominator is the length of the reference, which is why insertions can push WER above 100%.
WaveNet-style models stack blocks of causal convolutions with kernel size 2 and dilations . How many samples, including the current one, can an output of a stack of 3 such blocks depend on?
- 1,024
- 3,072
- 30
- 3,070
Show the answer
D. 3,070
The receptive field is . Each block adds , so three blocks give samples, about 0.19 s at 16 kHz.
A neural codec produces 75 frames per second, and each frame is coded with 8 codebooks of 1,024 entries each. What is its bitrate?
- 600 bits/s
- 6 kbit/s
- 614 kbit/s
- 75 kbit/s
Show the answer
B. 6 kbit/s
Each code index carries bits, so bits per second. A 16-bit, 24 kHz waveform needs 384 kbit/s, 64 times more.
Go deeper
- Speech Recognition · Spectrograms, CTC and sequence-to-sequence models.
- Speech Synthesis · From vocoders to neural voices.
- Audio & Music Generation · Tokenizing sound and generating it.
Further reading
- D. Jurafsky & J. H. Martin, Speech and Language Processing, chapter on automatic speech recognition and text-to-speech (3rd ed. draft).
- A. Graves, S. Fernández, F. Gomez & J. Schmidhuber, "Connectionist temporal classification: Labelling unsegmented sequence data with recurrent neural networks," ICML (2006).
- A. van den Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior & K. Kavukcuoglu, "WaveNet: A generative model for raw audio," arXiv:1609.03499 (2016).
- A. Radford, J. W. Kim, T. Xu, G. Brockman, C. McLeavey & I. Sutskever, "Robust speech recognition via large-scale weak supervision," ICML (2023).