Sub topic 2
Audio basics you need before calling an API
This chapter assumes you can write basic Python, call an SDK-based API with a key from an environment variable, and have opened an MP3 or WAV file before. It also assumes you can run a command-line tool such as ffmpeg. You don't need any signal-processing background.
Speech APIs accept files, and most failures in a first speech app come from the file, not the API call. A recording can be too large, in a format the service rejects, or recorded at a quality that hurts accuracy. This chapter explains how audio is stored, so you can predict file sizes and pick formats before you send anything.
From sound to numbers
A microphone produces a continuously varying voltage. A computer can only store a list of numbers, so the voltage is measured many times per second. Each measurement is a sample. Three settings describe the result.
- Sample rate is the number of samples per second, in hertz (Hz). CD audio uses 44,100 Hz. Telephone audio uses 8,000 Hz. Most speech models work well at 16,000 Hz.
- Bit depth is the number of bits used for each sample. 16 bits is common and gives 65,536 possible levels.
- Channels is the number of separate signals. Mono has one. Stereo has two, left and right.
A sample rate of N Hz can represent frequencies up to N/2 Hz (the Nyquist limit). Human speech carries most of its information below about 8 kHz, so 16 kHz covers it. Recording speech at 44.1 kHz stereo mostly adds bytes, not information. Services typically resample your audio internally anyway, so you pay in upload time and file size for detail the model never uses.
Raw, uncompressed samples are called PCM (pulse-code modulation). Its size is easy to compute:
bytes per second = sample rate × (bit depth / 8) × channels
| Format | Calculation | Bytes per second | Per minute |
|---|---|---|---|
| 16 kHz, 16-bit, mono | 16,000 × 2 × 1 | 32,000 | about 1.9 MB |
| 44.1 kHz, 16-bit, stereo | 44,100 × 2 × 2 | 176,400 | about 10.6 MB |
| 8 kHz, 16-bit, mono | 8,000 × 2 × 1 | 16,000 | about 1 MB |
An hour of CD-quality stereo PCM is roughly 635 MB. That is why nobody uploads raw PCM for long recordings.
Codecs and containers
Two ideas are often confused, and the difference matters when an API rejects a file.
- A codec (coder-decoder) is the method that turns samples into a compressed stream of bytes, and back. Examples are MP3, AAC, Opus, and FLAC.
- A container is the file wrapper. It holds one or more streams plus metadata such as the codec, sample rate, and duration. Examples are WAV, Ogg, M4A/MP4, and WebM.
Some names cover both. An .mp3 file is MP3-encoded audio in a minimal wrapper. A .wav file is usually a container around PCM, but it can hold other codecs. A .webm file from a browser usually contains Opus audio.
The common formats compare as follows.
| Format | Compression | Typical use | Notes for speech APIs |
|---|---|---|---|
| WAV (PCM) | None | Recording, editing | Accurate but large. Convert before uploading long audio. |
| FLAC | Lossless | Archiving | About half the size of WAV with identical samples. |
| MP3 | Lossy | General sharing | Widely accepted. A good default for upload. |
| M4A (AAC) | Lossy | Phone recordings | Accepted by many services. Common from voice memo apps. |
| Opus in WebM or Ogg | Lossy | Browser recording, calls | Efficient at low bitrates. Very good for speech. |
Lossy compression discards detail the ear is unlikely to miss, so the file shrinks and the original cannot be recovered exactly. Lossless compression shrinks the file and restores every sample exactly. For transcription, moderate lossy compression of speech costs little accuracy. Heavy compression, such as very low bitrates on noisy audio, can raise errors.
Always check which formats your provider accepts. The list differs between providers and changes over time. As one example, OpenAI's transcription documentation has listed MP3, MP4, MPEG, MPGA, M4A, WAV, and WebM, with a 25 MB upload limit. Treat figures like these as values to verify in the current documentation, not constants to hard-code from memory.
Bitrate and file size
Lossy codecs are configured by bitrate, the number of bits of compressed data per second of audio, written in kbps. Compressed size follows directly:
bytes = bitrate in bits per second / 8 × duration in seconds
This is the estimate you need when a service limits upload size. The function below turns it into code.
def max_minutes(limit_bytes: int, bitrate_kbps: int) -> float:
"""Longest recording, in minutes, that fits under a size limit."""
bytes_per_second = bitrate_kbps * 1000 / 8
return limit_bytes / bytes_per_second / 60
LIMIT = 25 * 1000 * 1000 # a 25 MB limit, counted as 25 million bytes
for kbps in (32, 64, 128, 192):
print(f"{kbps:>3} kbps -> {max_minutes(LIMIT, kbps):5.1f} minutes")Running it prints:
32 kbps -> 104.2 minutes
64 kbps -> 52.1 minutes
128 kbps -> 26.0 minutes
192 kbps -> 17.4 minutesA voice memo saved at 128 kbps would hit a 25 MB limit in about 26 minutes, while the same speech at 32 to 64 kbps mono would last much longer. Lowering the bitrate is the cheapest fix for a size problem, and the next chapters cover chunking for recordings that remain too large.
Duration also drives cost. Transcription is usually billed per minute of audio, so a smaller file does not make it cheaper, but trimming silence does.
Inspecting a file before you send it
Guessing settings leads to surprises, so read them from the file. Python's standard library can read PCM WAV files. The script below writes a two-second 440 Hz test tone and then inspects it. It needs no input file.
import math
import struct
import wave
RATE = 16000
# Create a 2-second, 16 kHz, 16-bit mono test tone.
with wave.open("tone.wav", "wb") as w:
w.setnchannels(1)
w.setsampwidth(2) # bytes per sample, so 2 means 16-bit
w.setframerate(RATE)
samples = (
struct.pack("<h", int(12000 * math.sin(2 * math.pi * 440 * n / RATE)))
for n in range(RATE * 2)
)
w.writeframes(b"".join(samples))
# Read the settings back.
with wave.open("tone.wav", "rb") as w:
rate = w.getframerate()
channels = w.getnchannels()
width = w.getsampwidth()
frames = w.getnframes()
print(f"sample rate : {rate} Hz")
print(f"channels : {channels}")
print(f"bit depth : {width * 8}")
print(f"duration : {frames / rate:.2f} s")
print(f"audio bytes : {frames * width * channels}")The output reports 16,000 Hz, 1 channel, 16 bits, 2.00 s, and 64,000 audio bytes. That matches the formula: 16,000 × 2 × 1 × 2 seconds. The file on disk is 44 bytes larger because of the WAV header.
The wave module only reads uncompressed PCM WAV. For MP3, M4A, or WebM, use ffprobe, which ships with FFmpeg:
ffprobe -hide_banner meeting.m4aIts output lists the container, codec, sample rate, channel layout, bitrate, and duration.
Preparing audio with FFmpeg
One command covers most preparation for speech work: downmix to mono, resample to 16 kHz, and encode as a modest-bitrate MP3.
ffmpeg -i input.m4a -ac 1 -ar 16000 -b:a 48k output.mp3-ac 1sets one channel.-ar 16000sets the sample rate to 16 kHz.-b:a 48ksets the audio bitrate to 48 kbps.
At 48 kbps, a 25 MB limit allows a bit over an hour of audio. Run the conversion once, and send the result.
Downmixing needs care. If the two channels hold different speakers, as in a recording with one party on each side, mixing them into one channel loses the ability to tell who spoke. Keep the stereo file, or split the channels into separate files, if you need that separation.
Common problems
- Wrong extension. Renaming
call.webmtocall.mp3does not convert it. Services usually inspect the content, but some check the filename, so a mismatch gives an "invalid file format" error. Convert the file properly. - Raw PCM with no header. A file of bare samples has no container, so nothing says the sample rate or bit depth. Wrap it in WAV first.
- Video files. Uploading an MP4 sends the video track too. Extract the audio with FFmpeg to cut upload time.
- Clipping. If the input level is too high, peaks are cut off and the distortion cannot be undone. Lower the recording gain instead of fixing it afterward.
- Low sample rate or heavy compression. Audio from an 8 kHz phone line transcribes worse than 16 kHz audio. Upsampling it afterward does not recover the lost detail.
- Long silences. They add duration and cost. Trim leading and trailing silence where you can.
What to carry forward
The next chapter sends a file to a transcription endpoint. Before that call, you should be able to say what the file's sample rate, channel count, codec, and container are, and estimate its size. Those four facts explain most rejected uploads and most accuracy surprises.
Exercise
A recording is 40 minutes long, saved as MP3 at 128 kbps. Your provider limits uploads to 25,000,000 bytes. Does the file fit? If it doesn't, what is the highest bitrate, in kbps, that would fit when you re-encode it?
Show answer
At 128 kbps the file needs 128,000 / 8 = 16,000 bytes per second. Forty minutes is 2,400 seconds, so the file is 38,400,000 bytes, which exceeds the limit. To fit, the bytes per second must be at most 25,000,000 / 2,400, about 10,417. That is about 83,333 bits per second, so any bitrate up to roughly 83 kbps fits. A standard choice such as 64 kbps (about 19,200,000 bytes) leaves some margin.
Exercise
Why can an uncompressed WAV recording of speech at 44.1 kHz stereo be converted to 16 kHz mono without hurting transcription much, and when would converting to mono be a mistake?
Show answer
Speech carries most of its information below about 8 kHz, which a 16 kHz sample rate can represent, and a single speaker's voice does not need two channels. The conversion cuts the data to roughly a sixth. Mono is a mistake when the channels separate different speakers, because mixing them loses who said what.