LevelUpWith

Explore / Voice and Realtime AI Agents: From Mic to Phone Line / Lesson 2

Lesson 2: Digital Audio Basics: Samples, Rates and Bits

Understand raw PCM audio (sample rate, bit depth, channels) and why voice systems mostly run at 8, 16, 24 or 48 kHz.

Free to read, no account needed. Part of Voice and Realtime AI Agents: From Mic to Phone Line.

By the end of this level you'll be able to

  • Work out the byte size of one second of 16 kHz, 16-bit mono PCM in Python and in TypeScript
  • Capture microphone audio, save it as a WAV file and inspect its header
  • Explain how the sample rate limits which frequencies survive and why 8 kHz phone audio sounds muffled

Sound as a list of numbers

In Level 1 we followed a spoken conversation from one person's mouth to the other person's ear. Now we look at what that audio becomes once it reaches your code. The answer is plain: a long list of integers.

A microphone turns changes in air pressure into a changing voltage. An analogue-to-digital converter measures that voltage at a fixed rate and writes each measurement down as a number. That stream of raw measurements is called PCM (pulse-code modulation). Every voice API you will use works with PCM under the hood, including STT engines, TTS engines and speech-to-speech models.

Three settings describe a PCM stream completely:

Setting Meaning Typical voice value
Sample rate Measurements per second (Hz) 8,000 / 16,000 / 24,000 / 48,000
Bit depth Size of each measurement 16-bit signed integer (values -32,768 to 32,767)
Channels Separate streams recorded together 1 (mono) for voice agents

If you get any one of these wrong, the audio comes out as chipmunk squeaks, slow-motion growling or loud static. Many "the model sounds broken" bug reports come down to a rate mismatch.

Worked example: how many bytes is one second?

The formula is sample_rate × bytes_per_sample × channels. Here it is in Python:

def pcm_bytes_per_second(sample_rate: int, bit_depth: int, channels: int) -> int:
    bytes_per_sample = bit_depth // 8      # 16 bits -> 2 bytes
    return sample_rate * bytes_per_sample * channels

print(pcm_bytes_per_second(16_000, 16, 1))   # 32000  -> typical STT input
print(pcm_bytes_per_second(24_000, 16, 1))   # 48000  -> typical model output
print(pcm_bytes_per_second(8_000, 16, 1))    # 16000  -> phone audio, as 16-bit PCM
print(pcm_bytes_per_second(48_000, 16, 2))   # 192000 -> stereo music/WebRTC-grade

And the same thing in TypeScript:

function pcmBytesPerSecond(sampleRate: number, bitDepth: number, channels: number): number {
  return sampleRate * (bitDepth / 8) * channels;
}

const perSec = pcmBytesPerSecond(16_000, 16, 1); // 32000
console.log(`1 s = ${perSec} B, 1 min = ${(perSec * 60) / 1e6} MB`); // 1 min = 1.92 MB

So one second of 16 kHz, 16-bit mono is 32,000 bytes, and a minute is about 1.9 MB before any compression. Keep that number in mind. It tells you how much bandwidth a live call needs and how quickly recordings fill up storage.

Gotcha: the byte count says nothing about the format. Raw PCM bytes don't record their own rate or bit depth. If you send 16 kHz audio to an API that expects 24 kHz, it plays back fast and high-pitched, with no error raised.

Why 8, 16, 24 and 48 kHz?

The key rule is the Nyquist limit: a sample rate can only represent frequencies up to half of itself.

  • 8 kHz keeps sound up to 4 kHz. This is classic telephony: the ITU G.711 standard samples at 8,000 Hz and carries roughly the 300–3,400 Hz voice band. Audio from a phone line (for example, Twilio Media Streams) reaches you at 8 kHz mono.
  • 16 kHz keeps sound up to 8 kHz. This is "wideband" speech and the usual choice for speech recognition. Gemini's Live API, for example, takes 16-bit PCM input at 16 kHz.
  • 24 kHz keeps sound up to 12 kHz. This is common for model output. OpenAI's Realtime API defaults to 24 kHz 16-bit mono PCM, and Gemini Live outputs at 24 kHz.
  • 48 kHz keeps sound up to 24 kHz, which covers everything humans hear. Browser and WebRTC audio usually runs at this rate.

Why phone audio sounds muffled: much of what tells "s" apart from "f", and "th" apart from "s", is hiss-like energy above 4 kHz. At 8 kHz all of that is removed. Vowels come through fine, but consonants blur. That is why people spell names out on phone calls ("S for Sugar"), and why STT accuracy on calls drops for spelled-out codes and email addresses. Raising the sample rate later can't bring that detail back, because it was never recorded.

Pitfall: frequencies above the Nyquist limit don't just disappear. If nothing filters them out before sampling, they fold back as false lower tones. This is called aliasing. Proper converters and resamplers filter first. Skipping every other sample to "downsample" does not filter, so it adds aliasing.

Walkthrough: record the mic and save a WAV

Raw PCM has no labels, so we usually save it inside a WAV file, which puts a small header in front of the samples. Install the tools with pip install sounddevice numpy:

import wave
import sounddevice as sd

RATE, CHANNELS, SECONDS = 16_000, 1, 3

print("Speak now...")
audio = sd.rec(int(SECONDS * RATE), samplerate=RATE,
               channels=CHANNELS, dtype="int16")  # NumPy array of int16 samples
sd.wait()                                          # rec() is non-blocking: wait for it

with wave.open("hello.wav", "wb") as wf:
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(2)         # bytes per sample: 16-bit
    wf.setframerate(RATE)
    wf.writeframes(audio.tobytes())  # little-endian on x86/ARM

print("samples:", len(audio), "bytes:", audio.nbytes)  # samples: 48000 bytes: 96000

Three seconds × 32,000 B/s = 96,000 bytes of samples, which matches the formula.

Walkthrough: read the header in TypeScript (Node)

A basic PCM WAV has a 44-byte header made of three parts: a RIFF chunk, a fmt chunk and a data chunk. All the numbers in it are little-endian.

import { readFileSync } from "node:fs";

const buf = readFileSync("hello.wav");
console.log({
  riff:          buf.toString("ascii", 0, 4),   // "RIFF"
  wave:          buf.toString("ascii", 8, 12),  // "WAVE"
  fmtId:         buf.toString("ascii", 12, 16), // "fmt "
  audioFormat:   buf.readUInt16LE(20),          // 1 = PCM
  channels:      buf.readUInt16LE(22),          // 1
  sampleRate:    buf.readUInt32LE(24),          // 16000
  byteRate:      buf.readUInt32LE(28),          // 32000  <- our formula!
  bitsPerSample: buf.readUInt16LE(34),          // 16
  dataId:        buf.toString("ascii", 36, 40), // "data"
  dataBytes:     buf.readUInt32LE(40),          // 96000
});

The header stores byteRate directly, and it equals the 32,000 you worked out earlier.

Production note: the fixed 44-byte layout is common but not guaranteed. Some tools add extra chunks such as LIST metadata, which pushes the data chunk further along. Robust code walks through the chunks by ID and size. Also, streaming APIs usually want raw PCM, so a WAV header sent by mistake gets played as a short click of noise.

Hands-on exercise

  1. Run the Python recorder at RATE = 16_000, then again at 8_000. Say "sixty-six, fifty-five, Steph, Seth" each time.
  2. Inspect both files with the TypeScript script and confirm that byteRate is 32,000 and 16,000.
  3. Play both files back. Write down which consonants become hard to tell apart at 8 kHz.
  4. Bonus: change the header of the 16 kHz file to claim sampleRate = 24000 (buf.writeUInt32LE(24000, 24), and update byteRate too), save it and play it. You have just reproduced the most common voice-agent audio bug.

Key takeaways

  • PCM audio is a stream of integer samples, described completely by sample rate, bit depth and channels.
  • Bytes per second = rate × (bits ÷ 8) × channels. 16 kHz 16-bit mono = 32,000 B/s.
  • A sample rate keeps frequencies only up to half its value (Nyquist). 8 kHz phone audio drops everything above 4 kHz, which is why consonants sound muffled.
  • In voice systems, 8 kHz is common for phone lines, 16 kHz for STT input, 24 kHz for model output and 48 kHz for browsers and WebRTC.
  • Raw PCM records no format information. A WAV header adds it, but don't assume it is always exactly 44 bytes.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Frames, Chunks and Streaming Buffers.

Create a free account →See the whole course

More like this