Whisper models expect audio in one particular form: 16,000 samples per second, one channel, 32-bit floating-point numbers between -1 and 1. Real input arrives in every other form: Kokoro's 24 kHz speech, 44.1 kHz stereo from a phone, 16-bit integers from a file. In this lesson you convert audio to the model's form in two ways, check that they agree, and write one function that the rest of the course can rely on.
Before You Start
You need the samples made in Sound as Numbers, in
~/voice-practice/data/samples. Create and enter this lesson's folder:
mkdir -p ~/voice-practice/convert-and-resample-audio
cd ~/voice-practice/convert-and-resample-audio
(PowerShell: New-Item -ItemType Directory -Force and Set-Location, as
before, with & "$HOME\voice-practice\.venv\Scripts\python.exe" for
Python.)
Three Conversions, Three Different Operations
Getting to 16 kHz mono float32 can involve three separate changes. They
are easy to confuse, and confusing them causes most audio bugs.
- Sample format: integer to float. A 16-bit sample of 16,384 means half
of full scale; as a float it is 0.5. Converting divides by 32,768. The
audio is unchanged; only its representation changes. soundfile does this
for you when you read with
dtype="float32". - Channels: stereo to mono. Averaging the two channels of each frame
keeps both sides of the sound in one channel, at the same rate and
length. The array goes from shape
(frames, 2)to(frames,). - Sample rate: 24,000 or 44,100 samples per second to 16,000. This is resampling: computing new samples at different moments in time from the old ones. The number of samples changes in proportion to the rates, and the duration stays the same.
What resampling does to the sound
A recording can only represent frequencies up to half its sample rate (the Nyquist frequency): 8,000 Hz at 16 kHz. Speech carries most of what a recogniser needs below that, which is why 16 kHz is common for speech models. A good resampler first removes anything above the new limit; if it did not, those frequencies would fold back into the audible range as distortion (aliasing). You do not need to write that filter: PyAV, which uses the FFmpeg libraries, does it for you (S58).
So converting Kokoro's 24 kHz speech to 16 kHz loses the content between 8 and 12 kHz, keeps everything below, and leaves the duration unchanged. A 3.84 s clip of 92,160 samples should become 3.84 s of 92,160 × 16,000 / 24,000 = 61,440 samples.
The tempting shortcut of just relabelling a 24 kHz file as 16 kHz is not resampling: the same samples are played more slowly, so the speech lasts longer and sounds deeper. The next lesson uses exactly that mistake as a case to diagnose.
Step 1: Convert Two Ways and Compare
Save this as convert.py:
"""Convert course samples to the format Whisper models expect: 16 kHz, mono, float32.
Converts speech-24k.wav and stereo-tones.wav two ways (PyAV's resampler,
and faster-whisper's own decoder), compares the results and saves the
PyAV versions next to the originals with a -16k-mono suffix.
"""
from pathlib import Path
import av
import numpy as np
import soundfile as sf
from faster_whisper.audio import decode_audio
SAMPLES = Path.home() / "voice-practice" / "data" / "samples"
TARGET_RATE = 16000
def to_mono(samples: np.ndarray) -> np.ndarray:
"""Average the channels of a (frames, channels) array; mono arrays pass through."""
return samples.mean(axis=1) if samples.ndim == 2 else samples
def resample(samples: np.ndarray, rate: int, target: int = TARGET_RATE) -> np.ndarray:
"""Resample mono float32 audio with PyAV (FFmpeg's resampler)."""
if samples.ndim != 1:
# A (frames, 2) array would otherwise be flattened into one interleaved channel.
raise ValueError(f"resample() needs mono audio, got shape {samples.shape}; call to_mono() first")
frame = av.AudioFrame.from_ndarray(samples.astype(np.float32).reshape(1, -1), format="flt", layout="mono")
frame.sample_rate = rate
resampler = av.AudioResampler(format="flt", layout="mono", rate=target)
pieces = [f.to_ndarray().reshape(-1) for f in resampler.resample(frame)]
pieces += [f.to_ndarray().reshape(-1) for f in resampler.resample(None)] # flush what it holds back
return np.concatenate(pieces)
def main() -> None:
for name in ("speech-24k.wav", "stereo-tones.wav"):
path = SAMPLES / name
samples, rate = sf.read(path, dtype="float32")
mono = to_mono(samples)
ours = resample(mono, rate)
theirs = decode_audio(str(path), sampling_rate=TARGET_RATE)
expected = len(mono) * TARGET_RATE / rate
print(f"{name}: {samples.shape} at {rate} Hz")
print(f" expected about {expected:.1f} samples at {TARGET_RATE} Hz")
print(f" PyAV resampler {len(ours)} samples, dtype {ours.dtype}")
print(f" faster-whisper {len(theirs)} samples, dtype {theirs.dtype}")
n = min(len(ours), len(theirs))
print(f" largest difference {np.max(np.abs(ours[:n] - theirs[:n])):.6f}")
out = path.with_name(path.stem + "-16k-mono.wav")
sf.write(out, ours, TARGET_RATE, subtype="FLOAT")
print(f" saved {out.name}")
if __name__ == "__main__":
main()
The blocks that matter:
to_mono()averages across axis 1, the channel axis of a(frames, channels)array, and passes mono arrays through unchanged.resample()first refuses anything but a one-dimensional (mono) array. Without that check, a stereo array would be flattened into a single channel with left and right samples interleaved: in the author's test, one second of stereo came back as two seconds of garbled audio, with no error at all. It then wraps the samples in a PyAVAudioFrame(packed 32-bit floats, mono, at the original rate), creates anAudioResamplerfor the target format and rate, and collects what it returns. A resampler holds back a few samples at the end so it can filter smoothly across them; the second call,resample(None), flushes them out. Forgetting the flush is a classic bug: the result is a few milliseconds short (S58).decode_audio()is faster-whisper's own function for the same job. It is what runs when you givetranscribe()a file path, so comparing against it shows that your conversion matches what the model would have done (S10). It uses PyAV too, which is why the course pins PyAV 18.1.0 (S14).- The comparison prints the expected length, both actual lengths and the largest difference between the two results, then saves the PyAV version as a 32-bit float WAV file.
Before you run it, predict the number of samples each method returns for
speech-24k.wav and for stereo-tones.wav.
~/voice-practice/.venv/bin/python convert.py
Illustrative output from the author's run:
speech-24k.wav: (92160,) at 24000 Hz
expected about 61440.0 samples at 16000 Hz
PyAV resampler 61440 samples, dtype float32
faster-whisper 61440 samples, dtype float32
largest difference 0.000015
saved speech-24k-16k-mono.wav
stereo-tones.wav: (44100, 2) at 44100 Hz
expected about 16000.0 samples at 16000 Hz
PyAV resampler 16000 samples, dtype float32
faster-whisper 16000 samples, dtype float32
largest difference 0.000015
saved stereo-tones-16k-mono.wav
- Both methods give exactly the predicted lengths: 61,440 samples (3.84 s) and 16,000 (1.00 s). Durations are preserved; only the number of samples per second changed.
- The largest difference is 0.000015, about half of one 16-bit step (1/32,768 ≈ 0.00003). The tiny difference comes from rounding, not from a different method.
- The stereo file became mono at 16 kHz in one step: channels averaged, then resampled.
If your lengths are a few samples short, the flush is missing. If they are far off, compare the rates printed on the first line with what you expected.
When Something Goes Wrong
| What you see | Likely cause | Safe next check |
|---|---|---|
TypeError: open() got an unexpected keyword argument 'metadata_errors' | PyAV 19 is installed | pip show av in the course environment; reinstall the course requirements |
ValueError: resample() needs mono audio | A stereo array passed to resample() | Call to_mono() first |
| A converted stereo file lasts twice as long as the original | A resampler without a mono check was given stereo samples | Convert to mono before resampling, and check durations |
| A result a few samples shorter than predicted | The resampler was not flushed | Add the resample(None) step |
FileNotFoundError | The samples have not been made | Run make_samples.py from Sound as Numbers |
Your Turn: One Function for Every File
Later lessons need one dependable way to turn any WAV file into model input.
Task. In this lesson's folder, write a script with a function
to_whisper_input(path) that returns 16 kHz mono float32 samples for any
WAV file, reusing to_mono() and resample() from convert.py (import
them). It must not resample a file that is already at 16 kHz. Run it on
tone-440.wav, stereo-tones.wav and speech-24k.wav and print each
result's length, duration, type and peak. Finally, show that reading the
16-bit tone as int16 and dividing by 32,768 gives the same values as
reading it as float32.
Hints, if you need them:
from convert import TARGET_RATE, resample, to_monoworks when your script is in the same folder asconvert.py.np.allclose(a, b)compares two arrays allowing for rounding.
Success: three durations of 1.000 s, 1.000 s and 3.840 s, all float32, and
True for the comparison.
Answer and Reasoning
"""Independent task solution: one function that prepares any WAV file for Whisper."""
from pathlib import Path
import numpy as np
import soundfile as sf
from convert import TARGET_RATE, resample, to_mono
SAMPLES = Path.home() / "voice-practice" / "data" / "samples"
def to_whisper_input(path: Path) -> np.ndarray:
"""Return the file as 16 kHz mono float32 samples in [-1, 1]."""
samples, rate = sf.read(path, dtype="float32")
mono = to_mono(samples)
return mono if rate == TARGET_RATE else resample(mono, rate)
for name in ("tone-440.wav", "stereo-tones.wav", "speech-24k.wav"):
out = to_whisper_input(SAMPLES / name)
print(f"{name}: {len(out)} samples, {len(out) / TARGET_RATE:.3f} s, dtype {out.dtype}, peak {np.max(np.abs(out)):.3f}")
# The same 16-bit file read as integers and scaled by 1/32768 gives the float values.
as_int, _ = sf.read(SAMPLES / "tone-440.wav", dtype="int16")
as_float, _ = sf.read(SAMPLES / "tone-440.wav", dtype="float32")
print("int16 / 32768 equals float32 read:", np.allclose(as_int / 32768, as_float))
Illustrative output:
tone-440.wav: 16000 samples, 1.000 s, dtype float32, peak 0.250
stereo-tones.wav: 16000 samples, 1.000 s, dtype float32, peak 0.238
speech-24k.wav: 61440 samples, 3.840 s, dtype float32, peak 0.553
int16 / 32768 equals float32 read: True
tone-440.wavis already 16 kHz, so it is returned unchanged with its peak of 0.250. Skipping the resampler avoids needless work and the tiny rounding it would add.- The stereo file's peak dropped from 0.25 to 0.238 because averaging two different tones (440 Hz and 660 Hz) means their peaks rarely coincide. Averaging channels can lower the level; it never raises it above the louder channel.
- The final line confirms that integer-to-float conversion is just a scale factor of 1/32,768.
Common mistakes: resampling before converting to mono (the course resampler
refuses; a resampler without that check silently doubles the duration),
and converting int16 values by dividing by 32,767 or 65,536.
Reset and Cleanup
The two -16k-mono.wav files in ~/voice-practice/data/samples can stay;
running convert.py again rewrites them. The lesson folder can be deleted
at any time, but keep convert.py if you want to reuse its functions.
References
- faster-whisper decoding files with PyAV (S10); the PyAV 19 change (S14)
- PyAV's
AudioResamplerand flushing withNone(S58) - soundfile's reading and types (S57)