Every speech model in this course receives audio as a list of numbers, and most audio bugs are really number bugs: the wrong rate, the wrong scale, the wrong shape. In this lesson you look inside audio files the way your code sees them, measure their length, level and size, and learn to predict those measurements before you run anything. You do not need to listen to anything: every check is a number.
Before You Start
You need the practice folder, environment and models from Set Up Python and the Speech Models. Create this lesson's folder and work in it:
mkdir -p ~/voice-practice/sound-as-numbers
cd ~/voice-practice/sound-as-numbers
In PowerShell: New-Item -ItemType Directory -Force "$HOME\voice-practice\sound-as-numbers"
and Set-Location into it; run Python as
& "$HOME\voice-practice\.venv\Scripts\python.exe".
What a Digital Recording Is
A microphone turns air pressure into a voltage that rises and falls with the sound. To store it, the recording device measures that voltage many times per second. Each measurement is a sample; the number of samples per second is the sample rate, measured in hertz (Hz).

Samples and levels. Each dot is one sample of a 440 Hz tone, the note A above middle C. At 16,000 samples per second there is one dot every 1/16,000 s, or 62.5 microseconds, so the 2.5 milliseconds shown hold 40 samples. The smooth line is the sound the samples describe.
Five terms describe any recording:
- Sample rate: samples per second. Speech models in this course expect 16,000 Hz; Kokoro produces 24,000 Hz; music is often 44,100 Hz.
- Channels: one for mono, two for stereo. Each channel has its own sample at every moment; the set of samples for one moment is a frame.
- Sample format (bit depth): how each number is stored. WAV files
commonly use 16-bit integers (
PCM_16), whole numbers from -32,768 to 32,767. Python code usually works with 32-bit floating-point numbers (float32) between -1.0 and 1.0, where 1.0 means the loudest value the file can hold. - Duration = frames ÷ sample rate.
- Level: how loud the numbers are. Full scale is the largest value the format can store, and levels are given in decibels relative to full scale (dBFS): dBFS = 20 × log₁₀(value). Full scale (1.0) is 0 dBFS; every halving of the value is about -6 dB, so 0.25 is about -12 dBFS. The peak level uses the largest absolute sample; the RMS level (root mean square, the square root of the average squared sample) uses the average energy and tracks perceived loudness better.
Values beyond full scale cannot be stored. Writing them to a 16-bit file clips them to the largest value, flattening the top of the wave.
A bridge: audio as NumPy arrays
Your code holds samples in a NumPy array (S26). Two attributes matter:
shape:(frames,)for mono, a one-dimensional array;(frames, channels)for stereo, so a second of 44.1 kHz stereo is(44100, 2).dtype: the type of every number, such asfloat32orint16.
Arithmetic applies to every element at once: samples * 0.5 halves the
level of the whole recording, and np.max(np.abs(samples)) finds the peak.
Predicting size
Uncompressed audio data takes frames × channels × bytes per sample. A 16-bit sample is 2 bytes, so one second of 16 kHz mono is 16,000 × 1 × 2 = 32,000 bytes. A WAV file adds a short header (44 bytes for the files in this lesson). Compressed formats such as MP3 store far less, but must be decoded back to samples before a model can use them.
Step 1: Make the Samples
Save this as make_samples.py:
"""Make the small sample set used by the audio lessons.
Writes four WAV files to ~/voice-practice/data/samples:
tone-440.wav 1.0 s of a 440 Hz tone, 16 kHz, mono, 16-bit, peak 0.25
stereo-tones.wav 1.0 s, 440 Hz left and 660 Hz right, 44.1 kHz, 16-bit
clipped-tone.wav the 440 Hz tone at 1.5 times full scale, saved as 16-bit
speech-24k.wav one sentence from Kokoro, 24 kHz, mono, 16-bit
Running it again rewrites the same files.
"""
from pathlib import Path
import numpy as np
import soundfile as sf
from kokoro_onnx import EspeakConfig, Kokoro
PRACTICE = Path.home() / "voice-practice"
MODELS = PRACTICE / "models"
OUT = PRACTICE / "data" / "samples"
def tone(frequency: float, seconds: float, rate: int, peak: float) -> np.ndarray:
t = np.arange(int(seconds * rate)) / rate # the time of every sample, in seconds
return (peak * np.sin(2 * np.pi * frequency * t)).astype(np.float32)
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
sf.write(OUT / "tone-440.wav", tone(440, 1.0, 16000, 0.25), 16000, subtype="PCM_16")
left, right = tone(440, 1.0, 44100, 0.25), tone(660, 1.0, 44100, 0.25)
sf.write(OUT / "stereo-tones.wav", np.stack([left, right], axis=1), 44100, subtype="PCM_16")
sf.write(OUT / "clipped-tone.wav", tone(440, 1.0, 16000, 1.5), 16000, subtype="PCM_16")
kokoro = Kokoro(str(MODELS / "kokoro" / "kokoro-v1.0.int8.onnx"), str(MODELS / "kokoro" / "voices-v1.0.bin"),
espeak_config=EspeakConfig(data_path=str(MODELS / "espeak-ng-data")))
speech, rate = kokoro.create("Dock seven at Riverside has five bikes and nine free spaces.",
voice="af_heart", lang="en-us")
sf.write(OUT / "speech-24k.wav", speech, rate, subtype="PCM_16")
for path in sorted(OUT.glob("*.wav")):
print(f"wrote {path.name}")
if __name__ == "__main__":
main()
tone() is the heart of it. np.arange(int(seconds * rate)) / rate lists
the time of every sample in seconds, and np.sin(2 * np.pi * frequency * t)
gives the wave's value at each of those times, scaled by peak. The four
files are chosen to differ in exactly one way each: a reference tone, a
stereo file at another rate, a deliberately clipped copy (written at 1.5
times full scale), and real-sounding speech from Kokoro at its own rate.
Run it (about 15 seconds; it writes four files, about 0.4 MB, to
~/voice-practice/data/samples):
~/voice-practice/.venv/bin/python make_samples.py
wrote clipped-tone.wav
wrote speech-24k.wav
wrote stereo-tones.wav
wrote tone-440.wav
Step 2: Report What Is Inside
Before running the report, predict for tone-440.wav: how many frames, how
many bytes of sample data, and what peak level in dBFS?
Save this as format_report.py:
"""Report what is inside every WAV file in a folder.
Usage: python format_report.py [folder] (default ~/voice-practice/data/samples)
"""
import sys
from pathlib import Path
import numpy as np
import soundfile as sf
def dbfs(value: float) -> float:
"""Decibels relative to full scale: 0 dBFS is the largest value a file can hold."""
return 20 * np.log10(value) if value > 0 else float("-inf")
def report(path: Path) -> None:
info = sf.info(path)
samples, rate = sf.read(path, dtype="float32") # mono: 1-D array; stereo: (frames, channels)
peak = float(np.max(np.abs(samples)))
rms = float(np.sqrt(np.mean(samples.astype(np.float64) ** 2)))
clipped = int(np.sum(np.abs(samples) >= 0.999))
bytes_per_sample = {"PCM_16": 2, "PCM_24": 3, "PCM_32": 4, "FLOAT": 4, "DOUBLE": 8}.get(info.subtype, 0)
predicted = info.frames * info.channels * bytes_per_sample
print(f"{path.name}")
print(f" sample rate {info.samplerate} Hz, {info.channels} channel(s), {info.subtype}, {info.frames} frames")
print(f" duration {info.frames / info.samplerate:.3f} s")
print(f" array shape {samples.shape}, dtype {samples.dtype}")
print(f" level peak {dbfs(peak):.1f} dBFS, RMS {dbfs(rms):.1f} dBFS")
print(f" clipping {clipped} samples at full scale ({clipped / samples.size:.1%})")
print(f" size {path.stat().st_size} bytes on disk; sample data {predicted} bytes")
def main() -> None:
folder = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "voice-practice" / "data" / "samples"
for path in sorted(folder.glob("*.wav")):
report(path)
if __name__ == "__main__":
main()
sf.info()reads the file's header: rate, channels, format and frame count, without loading the samples.sf.read(path, dtype="float32")loads the samples and converts them tofloat32in [-1, 1] whatever the file stores. Withoutdtype, soundfile returnsfloat64, which works but uses twice the memory (S57).peak,rmsanddbfs()apply the formulas above. The RMS sum is done infloat64to avoid rounding errors over long recordings.clippedcounts samples at or within a whisker of full scale. A few can occur naturally; many in a row mean clipping.predictedis the sample-data size from the formula, to compare with the size on disk.
Run it:
~/voice-practice/.venv/bin/python format_report.py
Illustrative output from the author's run:
clipped-tone.wav
sample rate 16000 Hz, 1 channel(s), PCM_16, 16000 frames
duration 1.000 s
array shape (16000,), dtype float32
level peak 0.0 dBFS, RMS -1.5 dBFS
clipping 8560 samples at full scale (53.5%)
size 32044 bytes on disk; sample data 32000 bytes
speech-24k.wav
sample rate 24000 Hz, 1 channel(s), PCM_16, 92160 frames
duration 3.840 s
array shape (92160,), dtype float32
level peak -4.8 dBFS, RMS -22.8 dBFS
clipping 0 samples at full scale (0.0%)
size 184364 bytes on disk; sample data 184320 bytes
stereo-tones.wav
sample rate 44100 Hz, 2 channel(s), PCM_16, 44100 frames
duration 1.000 s
array shape (44100, 2), dtype float32
level peak -12.0 dBFS, RMS -15.1 dBFS
clipping 0 samples at full scale (0.0%)
size 176444 bytes on disk; sample data 176400 bytes
tone-440.wav
sample rate 16000 Hz, 1 channel(s), PCM_16, 16000 frames
duration 1.000 s
array shape (16000,), dtype float32
level peak -12.0 dBFS, RMS -15.1 dBFS
clipping 0 samples at full scale (0.0%)
size 32044 bytes on disk; sample data 32000 bytes
How to read it:
tone-440.wavmatches the predictions: 16,000 frames, 32,000 bytes of sample data plus a 44-byte header, peak -12.0 dBFS. Its RMS is 3 dB lower than its peak, which is always true of a pure tone (its RMS is its peak divided by √2).stereo-tones.wavhas the shape(44100, 2): one row per frame, one column per channel. Its size is twice what a mono file of the same rate would be.clipped-tone.wavhas a peak of exactly 0 dBFS and more than half its samples at full scale. The tone was written at 1.5 times full scale and soundfile clipped every value beyond ±1 to the largest 16-bit value. The RMS of -1.5 dBFS is far above the clean tone's -15.1 dBFS: the wave has become almost a square wave. The file looks normal by its header; only the numbers show the damage.speech-24k.wavhas a peak of -4.8 dBFS but an RMS of -22.8 dBFS. Speech is mostly quieter than its loudest moments, and includes pauses.
The duration and size depend only on the files, so yours should match exactly. The speech file's level could differ slightly on another type of processor.
When Something Goes Wrong
| What you see | Likely cause | Safe next check |
|---|---|---|
FileNotFoundError or no output from the report | The samples folder does not exist yet | Run make_samples.py first and read its output |
Error processing file '.../phontab' | The espeak-ng data path problem from the setup lesson | Run check_setup.py; it reports the path length |
A shape like (44100, 2) where you expected (44100,) | The file is stereo | Check channels in the report; the next lesson converts it to mono |
| Values far beyond 1.0 after reading | The file stores floats that were never scaled | The Diagnose Audio Format Mistakes lesson covers this |
Your Turn: Predict, Then Check
Task. Without running anything, work out the number of frames and the
bytes of sample data in a file holding 2.5 seconds of stereo audio at
44,100 Hz in 16-bit PCM. Then write a short script that creates such a file
(any two quiet tones will do) in ~/voice-practice/sound-as-numbers, and
check your prediction with sf.info() or format_report.py.
Success: your predicted frames and bytes match the measured values exactly, and you can explain the 44 extra bytes on disk.
Answer and Reasoning
Frames = 2.5 × 44,100 = 110,250. Sample data = 110,250 frames × 2 channels × 2 bytes = 441,000 bytes. One way to check it:
"""Independent task solution: create a described file and compare it with the prediction.
Prediction for 2.5 s of stereo audio at 44,100 Hz in 16-bit PCM:
frames = 2.5 x 44,100 = 110,250
sample data = 110,250 x 2 x 2 bytes = 441,000 bytes
"""
from pathlib import Path
import numpy as np
import soundfile as sf
OUT = Path.home() / "voice-practice" / "sound-as-numbers" / "predicted.wav"
rate, seconds = 44100, 2.5
t = np.arange(int(seconds * rate)) / rate
left = 0.1 * np.sin(2 * np.pi * 300 * t)
right = 0.1 * np.sin(2 * np.pi * 500 * t)
sf.write(OUT, np.stack([left, right], axis=1).astype(np.float32), rate, subtype="PCM_16")
info = sf.info(OUT)
print(f"frames {info.frames} (predicted 110250)")
print(f"sample data {info.frames * info.channels * 2} bytes (predicted 441000); file {OUT.stat().st_size} bytes")
The author's run printed:
frames 110250 (predicted 110250)
sample data 441000 bytes (predicted 441000); file 441044 bytes
The file is 44 bytes larger than the sample data because of the WAV header, which records the rate, channels and format so that programs can read the numbers correctly. A common mistake is to forget the channel count, which halves the prediction; another is to count 16 bits as 16 bytes.
Reset and Cleanup
Keep ~/voice-practice/data/samples; the next two lessons use it. Running
make_samples.py again rewrites the same four files. The lesson folder,
including predicted.wav, can be deleted at any time. Nothing was
recorded and nothing left your computer.
References
- soundfile: reading, writing, default types and subtypes (S25, S57)
- NumPy 2.5.4 (S26)