Sub topic 5
Transcribing recordings that exceed size limits
This chapter assumes you can already send one audio file to a transcription endpoint (the previous chapters), that you know Python file handling, and that you know what MP3 and WAV files are. Here you will handle recordings too large for one request: how to split them, how to stitch the results, and what goes wrong at the seams.
Why long recordings need special handling
Hosted transcription endpoints cap the size of an uploaded file. For OpenAI's whisper-1 endpoint the cap is 25 MB per request. Other providers set different limits, and some also cap duration. Check the current documentation for your provider and model before you design around a number.
A request over the limit fails with an error response, usually an HTTP 413 or 400. The audio is not partially transcribed. Your code must therefore make sure each file is under the limit before it is sent.
File size depends on duration and bitrate, not on content. Rough figures:
| Format | Approximate rate | Minutes in 25 MB |
|---|---|---|
| WAV, 16-bit, 44.1 kHz stereo | about 10 MB per minute | about 2.5 |
| WAV, 16-bit, 16 kHz mono | about 1.9 MB per minute | about 13 |
| MP3, 128 kbps | about 1 MB per minute | about 26 |
| MP3, 64 kbps mono | about 0.5 MB per minute | about 52 |
Speech recognition does not need high fidelity. Speech is intelligible at 16 kHz mono, so the cheapest fix is often to re-encode the file before you split it. A one-hour meeting at 64 kbps mono is about 29 MB, close to the limit. Re-encoding sometimes removes the need to split, and sometimes it only reduces the number of chunks.
The splitting workflow
The overall plan has four steps.
- Check the file size. If it is under the limit, send it as it is.
- Optionally re-encode to a smaller format (mono, 16 kHz, modest bitrate).
- Cut the audio into chunks, each under the limit.
- Transcribe each chunk in order and join the texts.
Splitting with pydub
The pydub library loads audio into memory and lets you slice it by milliseconds. It relies on ffmpeg being installed on your machine to read and write MP3 and most other formats. Install both before running the code.
from pydub import AudioSegment
CHUNK_MS = 10 * 60 * 1000 # 10 minutes per chunk
audio = AudioSegment.from_file("long_recording.mp3")
chunk_paths = []
for index, start in enumerate(range(0, len(audio), CHUNK_MS)):
path = f"chunk_{index:03d}.mp3"
audio[start:start + CHUNK_MS].export(path, format="mp3")
chunk_paths.append(path)
print(chunk_paths)len(audio) returns the duration in milliseconds, so range(0, len(audio), CHUNK_MS) yields the start of each chunk. The last slice may be shorter than the others, and slicing past the end is safe. Zero-padded names such as chunk_007.mp3 keep the files in the correct order when sorted as text.
Ten minutes is a convenient length, but it is not guaranteed to be under the limit. A 10-minute chunk of 128 kbps MP3 is about 10 MB, which is fine. A 10-minute chunk exported as WAV stereo would be about 100 MB and would fail. The chunk length must be chosen from the bitrate of what you export, so verify it.
Verifying chunk sizes
Never assume a chunk is small enough. Check the size on disk after export and fail early, before you spend money or time on requests.
import os
LIMIT_BYTES = 25 * 1024 * 1024
SAFETY = 0.95 # leave headroom below the hard limit
def check_chunks(paths):
for path in paths:
size = os.path.getsize(path)
if size > LIMIT_BYTES * SAFETY:
raise ValueError(f"{path} is {size} bytes, over the safe limit")
check_chunks(["chunk_000.mp3", "chunk_001.mp3"])The safety margin guards against providers that count size slightly differently, such as including multipart request overhead. If a chunk is too large, lower the chunk duration and export again, rather than raising the limit.
You can also compute a chunk length from a target bitrate instead of guessing. At a constant bitrate, bytes per second equal bitrate divided by 8. For 128 kbps that is 16,000 bytes per second. Dividing a 24 MB budget by that figure gives about 1,573 seconds, so a 20-minute chunk is safe. Variable bitrate files can exceed that estimate, which is why you still check the real file.
Transcribing and joining the chunks
Once the chunks exist, transcribe them one at a time in order and concatenate the text. Reuse the retry helper from the chapter on errors and limits, or a simple loop like this one.
from openai import OpenAI
client = OpenAI()
def transcribe_chunks(paths):
texts = []
for path in paths:
with open(path, "rb") as f:
result = client.audio.transcriptions.create(model="whisper-1", file=f)
texts.append(result.text.strip())
return " ".join(texts)Keep the order explicit. If you later parallelize the requests with threads, collect results by chunk index and sort before joining, because requests finish in an unpredictable order.
Edge cases at the seams
Cutting at fixed times ignores what is being said. A cut can land in the middle of a word, so the first chunk ends with a fragment and the second begins with another. The model may transcribe each half as a different word or drop it. Several techniques reduce this damage.
Cut at silence
The pydub.silence module can find quiet stretches. Cutting there avoids splitting words.
from pydub import AudioSegment
from pydub.silence import detect_silence
audio = AudioSegment.from_file("long_recording.mp3")
silences = detect_silence(audio, min_silence_len=700, silence_thresh=-40)
print(silences[:5]) # list of [start_ms, end_ms] pairsmin_silence_len is in milliseconds. silence_thresh is in dBFS, and the right value depends on the recording, so you may need to tune it. For each target boundary, pick the nearest silence and cut in its middle. Add a maximum chunk length as a fallback so a recording with no pauses still gets split.
Overlap the chunks
Another approach is to start each chunk a few seconds before the previous one ended. The duplicated words are then removed when you join. This is more complex, because you must match the repeated text, and exact matching can fail when the model words the two copies differently. Silence-based cuts are usually simpler and more reliable.
Pass context with the prompt
The prompt option accepts text that guides style and vocabulary. Passing the last sentence or two of the previous chunk's transcript as the prompt for the next chunk helps keep spelling, names, and punctuation consistent. Treat it as a hint, not a guarantee. A very long prompt is truncated by the model, so send only the tail.
def transcribe_with_context(paths):
texts = []
previous_tail = ""
for path in paths:
with open(path, "rb") as f:
result = client.audio.transcriptions.create(
model="whisper-1",
file=f,
prompt=previous_tail,
)
text = result.text.strip()
texts.append(text)
previous_tail = text[-200:]
return " ".join(texts)Passing the prompt forces the chunks to run sequentially, since each depends on the one before. You trade speed for consistency.
Timestamps are relative to each chunk
If you request verbose_json with segment timestamps, each chunk's times start at zero. To get times in the original recording, add the chunk's start offset to every segment.
def offset_segments(segments, chunk_start_seconds):
return [
(seg.start + chunk_start_seconds, seg.end + chunk_start_seconds, seg.text)
for seg in segments
]If you cut at silence, the offsets are no longer multiples of a fixed length, so record the real start of every chunk as you export it.
Common mistakes
- Splitting WAV files by duration alone. Uncompressed audio is large, so fixed ten-minute chunks can still exceed the limit. Compress first or measure.
- Forgetting ffmpeg.
pydubraises an error or warns whenffmpegis missing, and MP3 export then fails. - Loading huge files into memory.
pydubdecodes everything into raw samples. A multi-hour file can use gigabytes of RAM. For very large inputs, useffmpegdirectly with its-f segmentoption, which splits on disk without loading the whole file. - Joining without spaces. Concatenating with an empty string glues the last word of one chunk to the first word of the next.
- Leaving temporary files behind. Delete chunk files when you are done, especially if the recording is sensitive.
The ffmpeg command-line splitter is worth knowing because it streams the file and never holds it all in memory:
ffmpeg -i long_recording.mp3 -f segment -segment_time 600 -c copy chunk_%03d.mp3With -c copy the audio is not re-encoded, so it is fast, but cuts snap to frame boundaries and the chunk durations are approximate.
Cost and retries
You pay for audio duration, so chunking does not change the total cost, apart from small overlaps. It does multiply the number of requests, which raises the chance of hitting a rate limit. Wrap each chunk request in a retry with backoff, and if one chunk fails permanently, report which index failed so you can resume without re-transcribing the others. Saving each chunk's text to disk as soon as it returns makes a long job restartable.
Exercise
A 90-minute meeting is stored as stereo WAV (16-bit, 44.1 kHz). Your API limit is 25 MB per file. You split it into 10-minute WAV chunks and every request fails. Why, and what two changes would fix it?
Show answer
A 10-minute stereo WAV at 44.1 kHz is roughly 100 MB, four times the limit, because uncompressed audio is about 10 MB per minute. Fix it by re-encoding to a compressed, speech-appropriate format such as mono MP3 at 64 kbps, which is about 0.5 MB per minute, and by choosing the chunk length from the bitrate of the exported files and checking each chunk's size on disk before sending it.
Exercise
You transcribe chunks that were cut every 10 minutes and request segment timestamps. A segment in the third chunk reports a start of 42.0 seconds. What is its start time in the original recording, and what should you do to avoid cutting words in half?
Show answer
The third chunk begins at 20 minutes, which is 1200 seconds, so the segment starts at 1242.0 seconds in the original recording. To avoid cutting words, choose cut points inside detected silences (for example with pydub's detect_silence), with a maximum chunk length as a fallback, and record each chunk's real start offset as you export it.