Sub topic 8
Streaming audio output
This chapter shows how to start playing synthesized speech before the API has finished generating it. It assumes you can already make a basic text-to-speech request, as covered in "Generating speech from text", and that you know how a response is split into chunks of bytes. You should also be comfortable with Python generators and context managers.
Why stream audio
A normal speech request waits for the whole clip. The server generates all the audio, sends it, and only then does your code receive the bytes. For a 20-second reply, you wait for all 20 seconds of audio to be generated before you hear the first word.
Streaming changes when your code sees the data. The server sends audio in chunks as it produces them, so the first chunk can arrive while later audio is still being generated. The metric that improves is time to first audio: the delay between sending the request and having something to play. Total generation time stays about the same.
This matters most in the voice loop. A user who finishes speaking and then waits several seconds for a reply assumes the app is broken. Cutting time to first audio is usually the biggest single improvement you can make to the perceived speed of a voice app.
What the SDK gives you
The OpenAI Python SDK offers with_streaming_response on the speech endpoint. It returns a context manager that keeps the HTTP connection open and lets you read the body incrementally.
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 to disk as it arrives instead of holding the full response in memory. This is the simplest form of streaming. It helps with memory use, but it does not help playback, because nothing plays the file until your code opens it. To start playback early, you have to consume the chunks yourself.
Consuming chunks directly
The response object also exposes iter_bytes, which yields chunks as they arrive. Each chunk is a bytes object that you can send to a player, a socket, or a WebSocket to a browser.
The diagram below shows the order of events for a streamed request.
Choosing a format for streaming
The output format decides how easy playback is when only part of the data has arrived.
| Format | Streaming behavior | Notes |
|---|---|---|
| `pcm` | Easiest to play immediately | Raw samples with no header. For OpenAI this is 24 kHz, 16-bit signed little-endian, mono. Confirm this in the current docs. |
| `wav` | Playable from the start | Has a header, so a player must accept a stream whose length is unknown or not yet final. |
| `mp3` | Works, but the player must decode frames | Small and widely supported. Pipe it to a decoder such as `ffplay`. |
| `opus` | Works, designed for internet streaming | Good for browsers and low-bandwidth links. |
| `aac`, `flac` | Works with a suitable decoder | Less common for live playback. |
For a local app, pcm is the simplest choice because you do not need a decoder. You only need to know the sample rate and sample format, which are the ideas from "Audio basics you need before calling an API". If you play it with the wrong sample rate, the voice sounds too fast or too slow. If you play it with the wrong sample width, you hear noise.
Playing PCM as it arrives
This example uses the sounddevice library, which you can install with pip install sounddevice. It writes each chunk to the sound card as soon as it arrives.
import sounddevice as sd
from openai import OpenAI
client = OpenAI()
SAMPLE_RATE = 24000 # Hz, matches the pcm output format
def speak(text):
leftover = b""
with sd.RawOutputStream(samplerate=SAMPLE_RATE, channels=1, dtype="int16") as out:
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input=text,
response_format="pcm",
) as response:
for chunk in response.iter_bytes(chunk_size=4096):
data = leftover + chunk
usable = len(data) - (len(data) % 2) # int16 needs 2 bytes per sample
out.write(data[:usable])
leftover = data[usable:]
speak("Your order has shipped and should arrive on Friday.")The leftover variable handles an edge case. Network chunks do not respect sample boundaries, so a chunk can end in the middle of a 2-byte sample. If you write an odd number of bytes, the samples that follow are shifted by one byte and the audio turns into static. The code keeps the extra byte and attaches it to the next chunk.
Starting speech before the LLM finishes
Streaming the speech is only half of the saving. In a voice loop, the chat model also takes time to write the reply. If you wait for the full reply text and then start synthesis, the delays add up.
You can stream the chat completion too, cut the text into sentences, and send each sentence to the speech endpoint as soon as it is complete.
import re
from openai import OpenAI
client = OpenAI()
SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
def speak_streamed_reply(messages):
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
stream=True,
)
buffer = ""
full_reply = ""
for event in stream:
if not event.choices:
continue
delta = event.choices[0].delta.content or ""
buffer += delta
full_reply += delta
parts = SENTENCE_END.split(buffer)
for sentence in parts[:-1]:
speak(sentence) # the speak() function from the previous example
buffer = parts[-1]
if buffer.strip():
speak(buffer)
return full_replyWith this design, the first sentence is spoken while the model is still writing the rest. The pipeline stages now overlap instead of running one after another.
This simple version has limits you should know about:
- Sentence detection is naive. The regex splits "Dr. Smith" after "Dr." and may speak the abbreviation as its own clip. A number such as "3.5" is safe because no whitespace follows the period.
- Playback blocks the loop. While
speakruns, the code is not reading the chat stream. The server buffers the tokens, so nothing is lost, but the next sentence is not ready in advance. A producer-consumer queue, with one thread synthesizing and one playing, removes the gaps. - Each sentence is a separate request. The voice can have slightly different intonation at the start of each clip, and every request pays its own connection and startup delay. Very short fragments make this worse, so consider joining fragments under about 5 words with the next sentence.
Failure modes
Streaming adds failure cases that a single request does not have.
- Mid-stream errors. A connection can drop after you have already played half a sentence. The status code was already 200 when the stream started, so the failure shows up as an exception while iterating, not at the
createcall. Wrap the loop in error handling and decide whether to retry the whole sentence or skip it. - Partial files. If you use
stream_to_fileand the stream fails, you are left with a truncated file. Write to a temporary name and rename it after thewithblock succeeds. - Underruns. If chunks arrive slower than the player consumes them, you hear gaps. A small buffer, for example 200 to 300 ms of audio, before you start playback trades a little latency for smoother sound.
- Interruption. Users may speak over the reply. To stop cleanly, leave the
withblock early. This closes the connection, so the server stops sending and you stop paying for audio you will not use. Also stop the sound device so queued audio does not keep playing.
Quick checks
Exercise
Your streamed PCM playback sounds like static after a few seconds, although the first moments are fine. The code writes each network chunk directly to a 16-bit output stream. What is the likely cause, and how do you fix it?
Show answer
A chunk probably ended in the middle of a 2-byte sample, so every later sample is shifted by one byte. Keep any odd trailing byte in a leftover variable, prepend it to the next chunk, and write only an even number of bytes each time.
Exercise
You switch from a single speech request to streaming, and the total time to produce the full reply barely changes. Why is the change still useful in a voice app?
Show answer
Streaming reduces time to first audio. The user hears the start of the reply while the rest is still being generated, so the app feels faster even though total generation time is about the same.
Exercise
Why is it better to split a streamed chat reply into sentences than to send every token to the speech endpoint as it arrives?
Show answer
Single tokens are too short to synthesize well. Each request has its own overhead, and tiny fragments produce choppy speech with poor intonation. A sentence gives the model enough context for natural phrasing while still letting playback begin before the reply is finished.