Sub topic 2
Preparing audio: 16 kHz mono and log-Mel spectrograms
This chapter covers what happens to an audio file before Whisper's neural network sees it. It assumes you can run Python scripts and install packages with pip, and that you know WAV and MP3 are file formats for sampled sound. It also assumes you have the earlier chapter's idea of speech recognition as turning audio into text. You don't need signal-processing theory. The chapter explains each term as it appears.
Why the model does not read raw audio files
An MP3 or WAV file stores a long list of numbers called samples. Each sample is the air pressure measured at one instant. The sample rate is how many of those measurements are taken per second. CD audio uses 44,100 per second, and a phone call uses about 8,000.
Whisper's network expects one fixed input shape. It cannot accept a variable sample rate, a variable number of channels, or a variable length. So a preparation stage converts every file into the same form:
- Decode the file and mix it down to one channel (mono).
- Resample to 16,000 samples per second (16 kHz).
- Pad or cut the audio to a 30-second window.
- Convert the waveform into a log-Mel spectrogram, a 2D grid of numbers.
Step 1: mono and 16 kHz
Mono
A stereo file has two channels, left and right. Whisper uses one. The ffmpeg decoder averages the channels into one. This is fine for transcription, because the words are almost always the same in both channels. It matters for a recording with one speaker on each channel, such as some call-center files. Both voices end up in one stream, and you lose the channel as a way to tell speakers apart. If you need that, split the channels yourself before transcribing.
Why 16 kHz
The Nyquist limit says a signal sampled at rate R can represent frequencies only up to R/2. At 16 kHz that limit is 8 kHz. Most of the information that distinguishes speech sounds lies below 8 kHz, so higher rates add data without much help to recognition. A lower rate would cost accuracy. Telephone audio at 8 kHz stops at 4 kHz, which is why fricatives such as "s" and "f" are easy to confuse on phone calls.
Upsampling does not recover lost detail. If you convert an 8 kHz phone recording to 16 kHz, the file has the right format, but nothing above 4 kHz exists in it. Expect worse accuracy than on true wideband audio.
Loading with the package
whisper.load_audio runs the ffmpeg command-line program and reads the result. This is why the first chapter's examples need ffmpeg installed.
import whisper
from whisper.audio import SAMPLE_RATE
audio = whisper.load_audio("audio.mp3")
print(audio.dtype) # float32
print(audio.shape) # (n_samples,)
print(len(audio) / SAMPLE_RATE) # duration in seconds
print(audio.min(), audio.max()) # roughly within -1.0 and 1.0The function returns a one-dimensional NumPy array of 32-bit floats. Internally ffmpeg outputs 16-bit signed integers, and the function divides by 32768 so values fall between -1 and 1.
You can do the same conversion on the command line, for example to prepare a batch of files once:
ffmpeg -i input.mp3 -ac 1 -ar 16000 -c:a pcm_s16le output.wavHere -ac 1 means one channel, -ar 16000 sets the sample rate, and pcm_s16le is plain 16-bit WAV.
Supplying your own array
model.transcribe also accepts a NumPy array or a PyTorch tensor in place of a filename. In that case the package does no resampling. It assumes the array is already 16 kHz mono floats. A common error is to pass an array loaded at the file's native rate:
import librosa
import whisper
model = whisper.load_model("base")
# Wrong: keeps the native rate (for example 44.1 kHz), so speech sounds
# slowed down and pitched low to the model.
# audio, sr = librosa.load("talk.wav", sr=None)
# Right: resample to 16 kHz mono during loading.
audio, sr = librosa.load("talk.wav", sr=16000, mono=True)
result = model.transcribe(audio) # float32 array
print(result["text"])The wrong version raises no error. The model just receives audio that is stretched in time and returns poor or empty text. If your text comes back as nonsense but the file plays fine, check the sample rate first.
Step 2: the 30-second window
Whisper's encoder always processes exactly 30 seconds, which is 480,000 samples at 16 kHz. Shorter audio is padded with zeros at the end, and longer audio is cut. The helper whisper.pad_or_trim does this.
import whisper
from whisper.audio import N_SAMPLES
audio = whisper.load_audio("audio.mp3")
window = whisper.pad_or_trim(audio)
print(N_SAMPLES) # 480000
print(window.shape) # (480000,)Padding is not harmful for short clips. The model was trained on short utterances padded the same way and learned to ignore the silent tail.
Step 3: from waveform to log-Mel spectrogram
A waveform shows loudness over time. Speech recognition works better on a picture of which frequencies are present at each moment. That picture is a spectrogram.
The short-time Fourier transform
The Fourier transform splits a signal into its frequencies. Applying it to a whole recording would lose timing, so the audio is cut into short, overlapping frames, and the transform is applied to each. This is the short-time Fourier transform (STFT). Whisper uses these settings:
| Setting | Value | Meaning |
|---|---|---|
| Sample rate | 16,000 Hz | Samples per second |
| `N_FFT` | 400 samples | Frame length, 25 ms |
| `HOP_LENGTH` | 160 samples | Step between frames, 10 ms |
| Window length | 30 s | 480,000 samples |
| Frames per window | 3,000 | 480,000 / 160 |
A new frame starts every 10 ms and each frame is 25 ms long, so neighboring frames overlap by 15 ms. A Hann window is applied to each frame to avoid sharp edges. Squaring the magnitude of the result gives the power at each frequency.
The Mel scale
The STFT gives 201 frequency values per frame (N_FFT / 2 + 1), spaced evenly. Human hearing is not even. We tell 200 Hz from 300 Hz easily but cannot tell 7,200 Hz from 7,300 Hz. The Mel scale spaces frequencies by perceived pitch, roughly linear at low frequencies and logarithmic at high ones.
A Mel filter bank is a set of overlapping triangular filters, wider at high frequencies. Each filter adds up the power in its band to give one number. Whisper stores the filter weights in a file shipped with the package. Most models use 80 filters, and the large-v3 model uses 128. This reduces 201 values per frame to 80 (or 128).
Log compression and normalization
Sound power spans many orders of magnitude, and human loudness perception is roughly logarithmic. So the code takes the base-10 logarithm, after clamping values to at least 1e-10 to avoid log of zero. Then it applies two more steps:
- Values more than 8.0 below the maximum in the window are raised to
max - 8.0. This floors very quiet background so it cannot dominate. - The result is shifted and scaled with
(x + 4) / 4, which puts most values roughly between -1 and 1.
Because of step 1, the normalization depends on the loudest part of each window. Two copies of the same clip at different volumes give nearly the same output, which makes the model fairly insensitive to recording level.
Computing it yourself
import whisper
from whisper.audio import N_FRAMES
model = whisper.load_model("base")
audio = whisper.load_audio("audio.mp3")
window = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(window, n_mels=model.dims.n_mels)
print(mel.shape) # torch.Size([80, 3000]) for base
print(N_FRAMES) # 3000
print(float(mel.min()), float(mel.max()))Pass n_mels=model.dims.n_mels rather than hard-coding 80. If you feed an 80-bin spectrogram to large-v3, the shapes do not match and PyTorch raises an error. If the number is right but the model is wrong, the error is easy to misread, so read the shape in the message.
You can look at the result with matplotlib. Time runs left to right and frequency bottom to top:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import whisper
audio = whisper.pad_or_trim(whisper.load_audio("audio.mp3"))
mel = whisper.log_mel_spectrogram(audio)
plt.figure(figsize=(10, 3))
plt.imshow(mel.numpy(), origin="lower", aspect="auto")
plt.xlabel("Frame (10 ms each)")
plt.ylabel("Mel bin")
plt.colorbar(label="Normalized log power")
plt.tight_layout()
plt.savefig("mel.png")Speech shows up as bright horizontal bands (harmonics of the voice) that move over time. Silence is a flat dark area, and the padded tail is uniform.
What the encoder does with the grid
The 80 x 3000 array goes into the encoder. Two 1D convolution layers come first, and the second has stride 2, which halves the time axis to 1,500 positions. Each position therefore covers 20 ms of audio. These positions, plus positional information, are the sequence the transformer reads. The next chapters cover the transformer in detail.
Common problems
FileNotFoundErrormentioning ffmpeg. Theffmpegprogram is not installed or is not on yourPATH. The Python package alone is not enough.- Garbled output from an array input. The sample rate was not 16 kHz, or the array was stereo with shape
(2, n)or(n, 2). Load withsr=16000, mono=True. - Integer arrays. Pass
float32values in the range -1 to 1. An array ofint16values up to 32,767 is far too loud for the normalization to make sense. - Wrong mel size. Use the model's
dims.n_mels. - Bad results on clipped or noisy audio. Preparation cannot repair clipping, heavy compression artifacts, or music that drowns the voice. Fix the source or use a cleaner recording.
- Slow decoding of very large files.
load_audioreads the whole file into memory. An hour of 16 kHz float32 audio is about 230 MB, which is fine, but many hours may not be. Split such files with ffmpeg first.
Exercise
A 12.5-second stereo MP3 recorded at 44.1 kHz is loaded with whisper.load_audio. (a) How many samples does the returned array have? (b) What shape does whisper.pad_or_trim(audio) return? (c) What shape does log_mel_spectrogram return for the base model, and how many seconds of audio does one column cover?
Show answer
(a) The file is converted to mono at 16 kHz, so the array has 12.5 x 16,000 = 200,000 samples. (b) It is padded with zeros to 30 seconds, so the shape is (480,000,). (c) The shape is (80, 3000) for the base model, with 80 Mel bins and 480,000 / 160 = 3,000 frames. Each column covers a 10 ms hop, which is 0.01 seconds, although each frame is 25 ms long.
Exercise
You load a recording with librosa.load("talk.wav", sr=None), which keeps its native 48 kHz rate, and pass the array to model.transcribe. What goes wrong, and how do you fix it?
Show answer
transcribe assumes an array is already 16 kHz mono, so it treats the 48 kHz samples as if they were 16 kHz. The model hears speech three times too slow and low in pitch, and the transcript is poor or empty. No error is raised. Fix it by loading with librosa.load("talk.wav", sr=16000, mono=True), or by passing the file path so that ffmpeg resamples it.