Sub topic 6
Generating speech from text
This chapter covers the text-to-speech (TTS) half of the pipeline. You send text to a speech endpoint and get audio back. It assumes you can write basic Python, have called an LLM chat API with an SDK, keep your API key in an environment variable, and know what an MP3 or WAV file is. The code uses the OpenAI Python SDK. Other providers have similar endpoints with different parameter names.
What a speech request does
A speech request takes three required inputs: a model, a voice, and the text to speak. The response body is encoded audio, not JSON. Your code has to save those bytes to a file or pass them to a player.
| Parameter | Purpose | Example |
|---|---|---|
| `model` | The synthesis model. It trades speed against quality. | `tts-1` |
| `voice` | A preset speaker identity. | `alloy` |
| `input` | The text to speak. The API limits its length. | A short sentence |
| `response_format` | The audio container and codec. | `mp3` |
Your first request
The example below writes the audio to reply.mp3. It uses the streaming response helper, which writes bytes to disk as they arrive. The next chapters build on this pattern.
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")The with block closes the HTTP connection when the file is written. Play reply.mp3 with any audio player to check the result.
Preparing text for speech
The model reads exactly what you give it. Text written for a screen often sounds wrong when spoken, and chat replies are a common source of this problem.
- Remove Markdown. Asterisks, pound signs, and table pipes may be skipped or read aloud.
- Spell out symbols and abbreviations that could be misread. Write "three dollars" instead of "$3" if the output sounds wrong.
- Keep sentences short. Long sentences give flat, rushed delivery.
- Do not send code blocks or long URLs. They are tedious to hear.
When an LLM produces the text, tell it in the system prompt to answer in plain spoken sentences. This works better than cleaning up the text afterward.
Limits to expect
- Input length. Each request accepts a limited number of characters. For long text, split it at sentence boundaries and send several requests. Never cut in the middle of a sentence, because the audio will have an audible jump.
- Billing. TTS is typically billed by input characters, so long text costs more. Check your provider's current pricing.
- No raw audio settings. You pick a format, not a sample rate or bit depth. The earlier chapter on audio basics explains how format choice affects size and compatibility.
Common errors
- Writing the response as text. Opening the output file in text mode, or printing
response.content, produces garbage. Audio is binary data. The helper above handles this for you. - Wrong file extension. If
response_formatiswavbut the file is namedreply.mp3, some players refuse to open it. Keep the two in step. - Empty or whitespace input. The API returns a 400 error. Check the text before the call.
- Missing key. An
AuthenticationErrorusually meansOPENAI_API_KEYis not set in the shell that runs your script.
Next step
You now have a function from text to an audio file. The next chapter covers how to choose a voice and output format. After that, you will see how to start playback before the whole file is generated.
Exercise
A teammate saves the speech response with open("reply.mp3", "w") and the file will not play. What is the likely cause, and what should they change?
Show answer
The file was opened in text mode, but audio is binary data. Open it in binary mode with "wb", or use response.stream_to_file("reply.mp3") from the streaming helper, which writes bytes correctly.
Exercise
Your LLM replies contain Markdown bullet lists and bold text, and the spoken output sounds awkward. Name two ways to fix this.
Show answer
Tell the model in the system prompt to answer in short plain spoken sentences with no formatting. Alternatively, strip Markdown symbols from the reply before sending it to the speech endpoint. Rewording at the source is usually more reliable.