7.4Audio: speech recognition, TTS & audio tokens
From pressure waves to spectrograms to discrete audio tokens, and how models like Whisper hear and modern TTS systems speak.
Sound is a very long list of numbers
A microphone measures air pressure, many thousands of times per second. Each measurement is a sample, and the list of samples is the waveform. The sample rate says how many samples you take per second: 16,000 per second (16 kHz) is standard for speech models, and music CDs use 44,100.
The sample rate limits which frequencies you can capture. A digital signal can only represent frequencies up to half its sample rate, the Nyquist frequency. At 16 kHz that’s 8 kHz, enough for intelligible speech, whose most important cues sit below about 4 kHz. Cymbals and the sparkle of music need more.
Here’s the problem for a Transformer. One second of 16 kHz audio is 16,000 numbers; a 30-second clip is 480,000. Each sample on its own means almost nothing: it’s one point on a wiggle. Compare that with text, where 30 seconds of speech might be 75 words, or about 100 tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit.. Audio models need a better representation, one that is shorter and closer to what our ears actually pick up.
A recording is like a seismograph trace: a single wiggly line that encodes everything but reveals little at a glance. Sheet music is different. Time runs left to right, pitch goes up the page, and each note says which tones sound when. A musician reads structure off it instantly.
A spectrogram is sheet music for any sound. Time runs left to right, frequency goes up, and brightness shows loudness. The mel scale is like laying the page out as piano keys, spaced by how different pitches sound rather than by raw hertz. Audio tokens go one step further: like a fixed set of musical symbols, a finite codebook from which any sound can be written down and played back.
From waveform to spectrogram
The Fourier transform decomposes a signal into sine waves: how much of each frequency it contains. Speech changes constantly, though, so a single transform over a whole sentence would blur every sound together. The fix is the short-time Fourier transformShort-time Fourier transform (STFT)Slicing a signal into short overlapping windows and taking the Fourier transform of each, which shows how its frequency content changes over time. (STFT):
- Cut the waveform into short, overlapping windows, typically 20–30 ms (speech sounds are roughly stable over that span).
- Taper each window’s edges with a smooth window function (such as a Hann window) so the cut doesn’t create fake frequencies.
- Run a fast Fourier transform (FFT) on each window and keep the magnitude (or power) at each frequency.
- Slide forward by a hop (often 10 ms) and repeat.
Stack the results side by side and you get a spectrogramSpectrogramA picture of sound showing how much energy each frequency has over time. Speech models often take log-mel spectrograms as input.: a 2D grid of time × frequency.
There is an unavoidable trade-off here. A long window contains many cycles, so it pins down frequency precisely, but it blurs anything that changes within the window. A short window catches fast changes but smears frequency. It’s a version of the uncertainty principle, and you can see it directly in the demo below.
The mel scale and the log
Two more steps turn a spectrogram into what speech models actually use.
The mel scale. Human hearing is far more sensitive to differences between low frequencies than between high ones. We easily hear 200 Hz vs 300 Hz, but 8,000 Hz vs 8,100 Hz is barely noticeable. The mel scaleMel scaleA perceptual frequency scale that is roughly linear below 1 kHz and logarithmic above, matching how humans hear pitch differences. warps frequency to match: roughly linear below 1 kHz and logarithmic above. A mel filterbank of overlapping triangular filters, spaced evenly in mels, pools the hundreds of FFT bins into a few dozen mel bands: 80 in the original Whisper models.
The log. Loudness perception is also roughly logarithmic, and raw power values span many orders of magnitude. Taking the log of each value (in practice, decibels) compresses that range so quiet consonants and loud vowels both show up.
The result is the log-mel spectrogram, the standard input for speech recognition. At a 10 ms hop it has 100 frames per second, each with 80 numbers. That’s 8,000 numbers per second instead of 16,000, and, more importantly, numbers that each mean something.
Color = log power (dB), brightest = loudest, 70 dB range. Long windows give sharp frequency lines but smear changes in time; short windows do the opposite. The original Whisper models use a 25 ms window, a 10 ms hop and 80 mel bands (large-v3 uses 128).
Things to try:
- Sine, then Chord. A pure tone is one bright horizontal line. The chord shows four lines, one per note. Shrink the window to 128 and the lines get fat: each frequency bin is now 125 Hz wide.
- Chirp, linear vs mel. On the linear axis the sweep is a straight diagonal. On the mel axis it bends: the low frequencies get far more vertical space, like your ear gives them.
- Vowel. You’ll see a stack of evenly spaced harmonics of the pitch, brighter in a few bands. Those bright regions are formants, resonances of the vocal tract that make “ah” sound different from “ee”. Switch vowels: the harmonics stay put, the formants move. Change the pitch: the harmonics move, the formants stay. This is why speech models care about the spectral envelope, not individual harmonics.
- Noise. Energy everywhere, no structure. Background noise looks like this, which is why it can bury quiet speech.
- Window 1024 on the chirp. The sweep smears into a thick band: the frequency changes too much within one 64 ms window.
Whisper: listening at scale
OpenAI’s Whisper (Radford et al., 2022) is the best-known modern speech recognizer, and its design is refreshingly standard. It is an encoder-decoder Transformer, like the original Transformer for translation:
- Audio is resampled to 16 kHz and cut into 30-second windows. Shorter clips are padded.
- Each window becomes an 80-channel log-mel spectrogram with 25 ms windows and a 10 ms hop: 3,000 frames.
- Two small convolution layers (the second with stride 2) turn this into 1,500 vectors, and the Transformer encoder processes them.
- The decoder generates text tokens autoregressively while cross-attending to the encoder output. Special tokens at the start tell it the language, the task (transcribe, or translate into English) and whether to emit timestamps.
What made Whisper stand out was the data: 680,000 hours of audio paired with transcripts found on the internet. Those transcripts are noisy, hence weak supervision, but the variety of accents, microphones and background conditions made the model unusually robust, and it works on new datasets without fine-tuning. About 117,000 of those hours covered 96 languages other than English, and another 125,000 paired non-English speech with English translations, which made one model both multilingual and a speech translator.
CTC vs sequence-to-sequence
Whisper’s decoder is one of two main ways to map audio frames to text. The other is CTCCTC (connectionist temporal classification)A loss for speech recognition that lets a model emit one label or a blank per audio frame and sums over all alignments that collapse to the correct transcript. (connectionist temporal classification, Graves et al., 2006), used for example when fine-tuning self-supervised encoders like wav2vec 2.0.
- CTC has no decoder. The encoder emits one symbol per frame, either a character, a sub-word or a special blank. To get the transcript, you merge repeats and drop blanks:
h h _ e _ l l _ l o→ “hello”. The loss sums over every frame-level alignment that collapses to the right answer. CTC is fast and strictly monotonic (it can’t skip or loop), but it predicts each frame nearly independently, so it has no built-in sense of language. - Seq2seq with attention (Whisper) uses a decoder that is effectively a language model conditioned on the audio. It produces fluent, well-punctuated text and can translate. The flip side: like any language model, it can hallucinate, for example by inventing plausible text during long silences or getting stuck repeating a phrase.
Speaking: TTS pipelines
Text-to-speech runs the other direction, and its architecture has changed a lot.
The classic two-stage pipeline first predicts a mel spectrogram from text or phonemes (Tacotron 2 and FastSpeech are well-known examples), then a vocoder (WaveNet, later the much faster HiFi-GAN) turns the spectrogram back into a waveform. This step is needed because a magnitude spectrogram throws away phase, and the vocoder has to invent a waveform consistent with it.
The token-based pipeline treats speech generation as language modeling: text → acoustic tokens → codec decoder → waveform. VALL-E (Microsoft, 2023) showed that a language model trained to predict audio-codec tokens can clone a voice from a 3-second sample, the same way an LLM continues a prompt. That requires turning audio into tokens, which is the next idea.
Neural audio codecs and residual vector quantization
A neural audio codecNeural audio codecA learned encoder-quantizer-decoder (e.g. SoundStream, EnCodec) that compresses audio into discrete tokens and reconstructs the waveform from them., such as Google’s SoundStream (2021) or Meta’s EnCodec (2022), has three parts:
- A convolutional encoder that downsamples the waveform to a much lower frame rate. EnCodec’s 24 kHz model produces 75 vectors per second.
- A quantizer that replaces each vector with integer codes from learned codebooks.
- A decoder that reconstructs the waveform from the codes. It is trained with reconstruction losses plus adversarial losses so the result sounds right, not just matches sample by sample.
The quantizer is the clever part. A single codebook would need astronomically many entries to describe audio finely. Residual vector quantizationResidual vector quantization (RVQ)Quantizing a vector with a chain of codebooks, where each codebook encodes the error left by the previous ones. Neural audio codecs use it to turn sound into a few discrete tokens per frame. (RVQ) uses a chain instead. Codebook 1 picks its nearest entry to the vector. Codebook 2 quantizes what’s left over, the residual error. Codebook 3 quantizes what that left, and so on. Each stage adds a few bits and shrinks the error.
Each stage picks the nearest of 16 entries to what is still missing, so every extra codebook costs 4 more bits and, on average, shrinks the error about 4×. Zoom in to see the later, finer codebooks. Dropping the last codebooks lowers the bitrate gracefully, which is how one codec can serve several bitrates.
Things to notice:
- One codebook gets you to the right neighborhood. Each extra codebook costs 4 more bits here and cuts the error about 4×.
- The codes are the tokens. The four or five small integers in the panel are all a receiver needs to rebuild , given the shared codebooks.
- Dropping later codebooks degrades gracefully. SoundStream trained with randomly dropped quantizers (“quantizer dropout”), so one model serves many bitrates. EnCodec’s 24 kHz model offers 1.5 to 24 kbps by using 2 to 32 codebooks of 1,024 entries each.
Codec tokens give language models a vocabulary for sound. There’s one wrinkle: each frame has several codes (one per codebook), so models must predict a small stack of tokens per time step. Different systems handle this by flattening the stack, predicting the first codebook autoregressively and the rest in parallel (as VALL-E does), or using a small extra Transformer per frame. Researchers also distinguish acoustic tokens, which capture exactly how something sounds, from semantic tokens (often from a self-supervised speech model), which capture what is said. AudioLM combined both. More recent codecs run at lower frame rates, such as 12.5 Hz for the Mimi codec used in Kyutai’s Moshi, so language models have fewer steps to predict.
Speech in, speech out
Put the pieces together and you can skip text entirely. A speech-to-speech model encodes the user’s audio, reasons over it, and emits codec tokens that a decoder turns into the reply’s audio. Moshi (2024) is an open example that listens and speaks at the same time. Removing the text bottleneck preserves tone and emotion and cuts latency. That is the subject of the next lesson.
MATH CORNER · optionalSTFT, mel and RVQ in numbers
STFT. For a frame starting at sample (hop ), with window of length ,
The power spectrogram is . Bins are spaced apart, so frequency resolution improves with longer windows while time resolution (one frame per samples) gets coarser.
Mel scale (the common HTK formula): .
Worked example: Whisper’s front end. Hz, window samples (25 ms), hop (10 ms).
| quantity | value |
|---|---|
| bin spacing | 40 Hz |
| FFT bins (0 to 8 kHz) | |
| frames in 30 s | |
| mel(1,000 Hz) | |
| mel(4,000 Hz) | |
| mel(8,000 Hz) |
So 0–1 kHz occupies about 35% of the mel axis (1,000 of 2,840 mels), even though it’s only 12.5% of the hertz range. With 80 evenly spaced mel bands, roughly 28 cover the region below 1 kHz.
RVQ bitrate. With codebooks of size at frame rate ,
EnCodec at 24 kHz: , (10 bits). With : bits/s = 6 kbps. With : 1.5 kbps. Uncompressed 16-bit audio at 24 kHz is 384 kbps, so 6 kbps is a 64× reduction. As tokens: 75 frames/s × 8 codes = 600 tokens per second of audio, versus a few text tokens per second of speech.
In code
Computing a Whisper-style log-mel spectrogram and running a pretrained model takes a few lines with standard libraries:
import numpy as np, librosa, whisper
y, sr = librosa.load("speech.wav", sr=16000) # resample to 16 kHz
S = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=400,
hop_length=160, n_mels=80) # 25 ms / 10 ms / 80 mels
log_mel = np.log10(np.maximum(S, 1e-10)) # (80, frames)
print(log_mel.shape) # ~100 frames per second
model = whisper.load_model("small") # openai-whisper package
print(model.transcribe("speech.wav")["text"])
def rvq_encode(x, codebooks): # x: (d,), codebooks: list of (K, d) arrays
codes, residual = [], x.copy()
for C in codebooks:
i = np.argmin(((C - residual) ** 2).sum(axis=1)) # nearest entry
codes.append(i)
residual = residual - C[i] # pass the error on
return codes, residual # codes are the "audio tokens"
- “Speech models listen to the raw waveform like we do.” Most speech recognizers, including Whisper, take a log-mel spectrogram. Some self-supervised encoders (wav2vec 2.0) do start from raw samples, but they immediately downsample them with convolutions into about 50 vectors per second.
- “A spectrogram contains everything in the audio.” A magnitude spectrogram discards phase, and mel pooling discards fine frequency detail. That’s why TTS systems need a vocoder or codec decoder to produce a waveform from it.
- “Whisper was trained on carefully transcribed audio.” It was trained on 680,000 hours of weakly supervised data, internet audio with whatever transcripts came with it. Scale and diversity made up for noise.
- “Audio tokens are like text tokens: one per word.” Codec tokens describe short frames of sound, often several codes per frame and hundreds per second. One spoken word can cost dozens of audio tokens.
Check your understanding
Q1.Audio is sampled at 16 kHz. What is the highest frequency it can represent?
Q2.You increase the STFT window from 256 to 1,024 samples. What happens?
Q3.Why do speech models use the mel scale?
Q4.In residual vector quantization, what does the second codebook encode?
Q5.A codec runs at 50 frames per second with 4 codebooks of 1,024 entries each. What is its bitrate?
Further reading
- paperRobust Speech Recognition via Large-Scale Weak Supervision (Whisper) — Radford et al. (2022): 680,000 hours, log-mel input, encoder-decoder Transformer.
- blogSequence Modeling with CTC — Awni Hannun's visual explanation of the CTC loss and decoding.
- paperSoundStream: An End-to-End Neural Audio Codec — Zeghidour et al. (2021): residual vector quantization and quantizer dropout.
- paperHigh Fidelity Neural Audio Compression (EnCodec) — Défossez et al. (2022): the codec behind many audio language models.
- paperNeural Codec Language Models are Zero-Shot Text to Speech Synthesizers (VALL-E) — TTS as language modeling over codec tokens.
- paperAudioLM: a Language Modeling Approach to Audio Generation — Semantic and acoustic tokens combined in one hierarchy.