Sub topic 8
Streaming audio output
This chapter assumes you can make a basic text-to-speech request and have the OpenAI Python SDK installed. It also assumes you know which output formats the speech endpoint offers. Here you will see how to start playback before synthesis finishes.
Why streaming matters
A normal speech request returns only after the whole clip is generated. A long reply can take several seconds to produce. The listener hears nothing until the last byte exists.
Streaming changes when the audio is delivered. The server sends bytes in chunks while it is still generating. Your code can write them to disk or hand them to a player right away. Total generation time stays about the same. Time to first audio drops.
Streaming to a file
The SDK's with_streaming_response wrapper does not read the whole body into memory. It gives you a response object you consume as bytes arrive.
from openai import OpenAI
client = OpenAI()
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input="Your order has shipped and should arrive on Friday.",
response_format="mp3",
) as response:
response.stream_to_file("reply.mp3")stream_to_file writes each chunk as it arrives. The with block closes the connection when the body ends or an error occurs. Note that a complete file on disk is only useful to a player once it is finished. To hear audio early, you must read the chunks yourself.
Reading chunks for playback
Use iter_bytes to receive pieces and pass them to a player or a network socket.
from openai import OpenAI
client = OpenAI()
total = 0
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input="Your order has shipped and should arrive on Friday.",
response_format="mp3",
) as response:
for chunk in response.iter_bytes(chunk_size=4096):
total += len(chunk)
# Replace this line with a write to your audio player or socket.
print(f"received {len(chunk)} bytes")
print(f"total: {total} bytes")Choosing a format for streaming
The format decides how easily a player can start on a partial stream.
| Format | Streaming behavior |
|---|---|
| `mp3` | Frames are self-contained, so most players start early. |
| `opus`, `aac` | Compact. Support for partial playback depends on the container and player. |
| `wav` | Simple and quick to start, but large. |
| `pcm` | Raw samples with no header. Easiest to feed to an audio device, but you must supply the sample rate and channel count yourself. |
For low latency, raw pcm or wav removes decoding work. For bandwidth-limited clients, mp3 or opus is smaller.
Common errors
- Reading
response.contentinside a streaming block. This forces a full read and removes the benefit. - Playing a file that is still being written. The player may stop at the current end of file. Feed it from the chunk loop instead.
- Ignoring mid-stream failures. A connection can drop after some bytes have arrived. Catch the exception and decide whether to discard the partial audio or retry.
- Assuming the first chunk arrives instantly. The model still needs time before it emits anything. Measure time to first byte, not total time.
Exercise
Exercise
A teammate streams a reply with stream_to_file, then starts playing reply.mp3 as soon as the call returns. Playback begins late, not early. Why, and what would you change?
Show answer
stream_to_file blocks until the whole body is written, so the call returns only after generation finishes. Playback therefore starts at the same time as in a non-streaming call. To start early, read the response with iter_bytes and send each chunk to the player as it arrives, or split the text into sentences and play each clip while the next is generated.