Sub topic 6
Generating speech from text
This chapter covers the text-to-speech (TTS) half of a speech pipeline. You send text to a hosted endpoint and get audio bytes back. It assumes you can write basic Python, have called a chat API with an SDK, keep API keys in environment variables, and know what an MP3 or WAV file is.
What a TTS request does
A text-to-speech endpoint takes a string and returns encoded audio. In a voice app it is the last stage. The speech-to-text (STT) stage turns the user's audio into text, the LLM writes a reply, and TTS turns that reply back into sound.
The request is small. It has four main fields:
| Field | Meaning | Example |
|---|---|---|
| `model` | Which synthesis model to run | `tts-1` |
| `voice` | A named preset voice | `alloy` |
| `input` | The text to speak | `"Your order has shipped."` |
| `response_format` | The container and codec of the returned bytes | `mp3` |
The response is not JSON. It is the raw audio file. Your code must write the bytes to disk, send them to a player, or pass them to a client. Treating the response as text is a common first mistake.
A first request
The example below sends one sentence and saves the result. It uses the streaming response helper in the OpenAI Python SDK, which writes bytes to the file as they arrive instead of holding the whole response in memory.
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")Run it with OPENAI_API_KEY set in your environment. When it finishes, reply.mp3 plays in any audio player.
The with block matters. It keeps the HTTP connection open while you read the body and closes it when the block exits. If you call stream_to_file outside the block, the connection may already be closed.
Choosing a voice
A voice is a preset identity, such as alloy, echo, or nova. You choose it by name. You do not tune pitch or timbre yourself. Voice names and the list of available voices vary by provider and model version, so check the current documentation before you hard-code one.
Practical points when you pick a voice:
- Listen to every candidate with a sentence from your real content. A voice that sounds good on "Hello, world" may sound odd on numbers, product names, or long sentences.
- Keep one voice per product surface. Switching voices between turns is jarring.
- Treat the voice choice as configuration, not code. Put it in a settings object so you can change it without a deploy.
Choosing an output format
The response_format field sets the container and codec. A codec is the method that compresses the sound. A container is the file wrapper around it. Chapter 2 covered both in more detail. The choice affects size, latency, and where the audio can play.
| Format | Compression | Typical use |
|---|---|---|
| `mp3` | Lossy | Default. Plays almost everywhere. |
| `opus` | Lossy | Low bitrate. Good for streaming and the web. |
| `aac` | Lossy | Common on mobile and in video. |
| `flac` | Lossless | Archiving, or when you will process the audio further. |
| `wav` | None | Low-latency playback. Large files. |
| `pcm` | None, headerless | Raw samples for your own audio pipeline. |
Two details cause real bugs:
pcmhas no header. The file does not say its sample rate or channel count, so you must know them from the provider's documentation. If you play it at the wrong rate, it sounds too fast or too slow.wavandpcmare large. A minute of uncompressed audio can be several megabytes, while the same minute as MP3 is far smaller. On slow links the size can cost more time than decoding saves.
A reasonable default is mp3 for files and opus or pcm for streaming to a live client. Match the format to what the playback side can decode.
Controlling speed
Many TTS endpoints accept a speed parameter. For the OpenAI endpoint it is a number from 0.25 to 4.0, with 1.0 as normal.
from openai import OpenAI
client = OpenAI()
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input="Please hold while I look that up.",
response_format="mp3",
speed=1.15,
) as response:
response.stream_to_file("hold.mp3")Small changes work best. Values near 1.1 to 1.25 shorten long answers without sounding rushed. Extreme values distort the voice. Test with your own content, and check the provider's documented range, since it can change.
Preparing the text
TTS reads exactly what you give it. Text that looks fine on a screen can sound wrong when spoken, and the model has no idea you meant something else. Chat model output is the usual source of trouble, because it is written for reading.
Common problems:
- Markdown. Asterisks, backticks, pound signs, and table pipes may be read aloud or cause odd pauses. Strip formatting before synthesis.
- URLs and code. A long URL read character by character is useless. Replace it with a short phrase such as "the link in the chat".
- Abbreviations, dates, and numbers. "3/4" could be a date or a fraction. "Dr." may be "Doctor" or "Drive". Spell out anything ambiguous.
- Long answers. Users do not want to listen to five paragraphs. Ask the LLM for short spoken replies in its system prompt.
A small cleanup function covers the basics:
import re
def to_speakable(text: str) -> str:
text = re.sub(r"```.*?```", " (code omitted) ", text, flags=re.DOTALL)
text = re.sub(r"`([^`]*)`", r"\1", text)
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
text = re.sub(r"https?://\S+", "the link", text)
text = re.sub(r"[*_#>|]+", "", text)
return re.sub(r"\s+", " ", text).strip()
print(to_speakable("See **the docs** at https://example.com/guide for `pip install`."))This prints See the docs at the link for pip install. The function is a starting point. It does not handle numbers or abbreviations, which depend on your domain.
Input limits and long text
Each request has a maximum input length. For the OpenAI endpoint it is 4,096 characters at the time of writing. Other providers set different limits, and limits change, so read the current documentation.
If your text can exceed the limit, split it at sentence boundaries, synthesize each piece, and play or join the results in order. Do not cut at a fixed character count, because you may split a word and produce an audible glitch at the seam.
import re
def split_for_tts(text: str, limit: int = 4000) -> list[str]:
sentences = re.split(r"(?<=[.!?])\s+", text)
chunks, current = [], ""
for sentence in sentences:
if current and len(current) + len(sentence) + 1 > limit:
chunks.append(current)
current = sentence
else:
current = f"{current} {sentence}".strip()
if current:
chunks.append(current)
return chunksThe function uses a limit below the real maximum to leave headroom. A single sentence longer than the limit still comes out as one oversize chunk, so add a fallback if your content can contain one.
Voice and tone can differ slightly between separate requests. For a short app reply this rarely matters. For long narration, keep the same model, voice, and speed in every chunk.
Errors and cost
TTS is billed by the number of input characters, not by audio length. A long reply costs more than a short one, and a retry costs again. Cap the length of text you send, and avoid synthesizing text the user will never hear.
Failures look like those of any other API call. Rate limit errors (HTTP 429) and timeouts are the common ones, and you handle them with retries and backoff. A later chapter covers that pattern for all speech calls. For now, set a client timeout so a stalled request does not hang your app:
from openai import OpenAI
client = OpenAI(timeout=30.0)Also cache audio for text you speak often, such as greetings or fixed error messages. Hash the text, voice, model, and format together as the cache key. The same inputs give you audio you can reuse at no extra cost.
Disclosure
The voice is synthetic. Providers' usage policies generally require you to make clear to users that they are hearing an AI-generated voice and not a human. Add a short notice in your interface or in the first spoken line. Do not use TTS to imitate a real person without their permission.
Common mistakes
- Reading
response.textorresponse.json()instead of saving the bytes. - Saving MP3 bytes under a
.wavname, so players fail. - Sending raw Markdown from the LLM.
- Hard-coding the voice and format across the codebase.
- Forgetting the character limit and getting a 400 error on long replies.
- Playing headerless
pcmat the wrong sample rate.
Exercise
Your voice app plays replies correctly in tests, but in production some long LLM answers fail with a 400 error, and others are read aloud with the word "asterisk" or with spoken URLs. Name the two preprocessing steps you should add before calling the TTS endpoint, and say where in the pipeline they go.
Show answer
Add a cleanup step that strips Markdown and replaces URLs and code with short spoken phrases, and a splitting step that breaks text longer than the endpoint's character limit into sentence-aligned chunks. Both run on the LLM's reply text after the chat call and before each TTS request. The chunks are then synthesized in order and played or joined in that order, using the same model, voice, and speed for every chunk.
Exercise
You need to stream synthesized audio to a browser client over a slow mobile network, and also archive each reply for later quality review. Which output format would you pick for each purpose, and why?
Show answer
For streaming, use a compressed format such as opus or mp3, because smaller payloads arrive sooner on a slow link. For the archive, use flac if you want lossless quality for review, or keep the same mp3 if storage cost matters more than fidelity. Uncompressed wav or pcm would add transfer time for streaming and use more storage, and pcm would also need the sample rate recorded separately.