Sub topic 7
Choosing voices and output formats
This chapter covers the three request parameters that shape the audio you get back from a text-to-speech (TTS) call: the voice, the output format, and the speaking speed. It assumes you have read the previous chapter and can make a basic speech request with the OpenAI Python SDK. It also assumes you know what sample rate, channels, and codecs are from the audio basics chapter. Model names, voice names, and limits change over time, so check the provider's current documentation before you hard-code them.
What you control in a speech request
A speech request has four main knobs.
| Parameter | What it controls | Typical values |
|---|---|---|
| `model` | Quality, latency, and which extra options exist | `tts-1`, `tts-1-hd`, `gpt-4o-mini-tts` |
| `voice` | The timbre and character of the speaker | `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, and others |
| `response_format` | The codec and container of the returned bytes | `mp3`, `opus`, `aac`, `flac`, `wav`, `pcm` |
| `speed` | Playback rate of the generated speech | `0.25` to `4.0`, default `1.0` |
Each choice has a cost in quality, size, latency, or compatibility. The sections below cover them in order.
Choosing a voice
A voice is a named preset. You do not train or tune it. You pick one by name, and the same name gives the same general character on every call. The built-in voices are tuned mainly for English but speak other languages, usually with an accent that follows the voice.
Voice names differ in availability between models. The older tts-1 and tts-1-hd models support a smaller set than gpt-4o-mini-tts, which adds more voices. If you pass a voice a model does not support, the API returns a 400-level error. Treat the voice as configuration, not as a constant buried in your code.
The only reliable way to choose a voice is to listen. Generate the same sentence with several voices and compare them on text that resembles your real content.
from pathlib import Path
from openai import OpenAI
client = OpenAI()
SAMPLE = "Your order has shipped and should arrive on Friday. Reply 1 to track it."
VOICES = ["alloy", "echo", "nova", "onyx"]
out_dir = Path("voice_samples")
out_dir.mkdir(exist_ok=True)
for voice in VOICES:
path = out_dir / f"{voice}.mp3"
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice=voice,
input=SAMPLE,
response_format="mp3",
) as response:
response.stream_to_file(path)
print(f"{voice}: {path.stat().st_size} bytes")Judge each sample on things that matter for your product, not only on whether it sounds pleasant:
- Numbers, dates, and names. Does the voice read "Friday" and "1" the way a listener expects?
- Pace and pauses. Does it leave room after a question?
- Fatigue. Play 30 seconds of continuous speech. Some voices are fine for a sentence and tiring for a paragraph.
- Consistency. Use one voice for one persona across your whole app, so users do not hear the assistant change identity.
Steering style with instructions
The gpt-4o-mini-tts model accepts an instructions parameter that describes how to speak, such as tone, pacing, or emotion. The tts-1 family does not support it. Check the current documentation for the exact support before relying on it.
from openai import OpenAI
client = OpenAI()
with client.audio.speech.with_streaming_response.create(
model="gpt-4o-mini-tts",
voice="coral",
input="I'm sorry about the delay. Your refund is on its way.",
instructions="Speak calmly and warmly, at a slightly slower pace.",
response_format="mp3",
) as response:
response.stream_to_file("apology.mp3")Instructions guide the delivery but do not guarantee it. Test them with the same listening process you use for voices.
Choosing an output format
The response_format parameter selects the codec and container of the returned bytes. The right choice depends on where the audio goes next.
| Format | Compression | Good for | Watch out for |
|---|---|---|---|
| `mp3` | Lossy | Default. Plays almost everywhere, small files | Slightly more decode overhead than raw formats |
| `opus` | Lossy | Streaming over the internet, low latency, WebRTC-style pipelines | Not every native player handles it |
| `aac` | Lossy | iOS, Android, and video workflows | Licensing and container quirks in some tools |
| `flac` | Lossless | Archiving, or further audio editing | Larger files than lossy formats |
| `wav` | None (PCM in a WAV container) | Simple, fast decoding, easy to process | Large files |
| `pcm` | None (raw samples) | Feeding a speaker or audio library directly | No header, so you must know the parameters |
Two rules cover most cases:
- Sending audio to a person's device over a network: use
mp3oropus. The files are small and nearly every client can play them. - Processing audio in your own code: use
wavorpcm. You skip a decode step, and you can inspect or edit the samples directly.
The decision flow looks like this:
Raw PCM needs parameters
A pcm response has no header. It is only a stream of samples, so no file player can tell how to interpret it. The documented parameters are 24 kHz sample rate, 16-bit signed samples, little-endian, mono. If you write those bytes straight to a .pcm or .wav filename, the result is either unplayable or plays as noise.
To make a playable file, wrap the samples in a WAV header with the standard library:
import wave
from openai import OpenAI
client = OpenAI()
pieces = []
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input="This is raw PCM wrapped in a WAV header.",
response_format="pcm",
) as response:
for chunk in response.iter_bytes():
pieces.append(chunk)
pcm_bytes = b"".join(pieces)
with wave.open("reply.wav", "wb") as wav_file:
wav_file.setnchannels(1) # mono
wav_file.setsampwidth(2) # 16-bit samples = 2 bytes
wav_file.setframerate(24000) # 24 kHz
wav_file.writeframes(pcm_bytes)
print(f"Wrote {len(pcm_bytes)} bytes of audio")If the result plays too fast, too slow, or as static, one of the three wave settings does not match the data. Streaming chunks can also split a sample in half, so write the bytes in order and do not reorder or drop any.
Compare formats on real output
File size depends on the text and the codec, so measure it instead of guessing.
from pathlib import Path
from openai import OpenAI
client = OpenAI()
TEXT = "Thanks for calling. Your appointment is confirmed for Tuesday at three."
FORMATS = ["mp3", "opus", "aac", "flac", "wav"]
for fmt in FORMATS:
path = Path(f"sample.{fmt}")
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
input=TEXT,
response_format=fmt,
) as response:
response.stream_to_file(path)
print(f"{fmt:5s} {path.stat().st_size:8d} bytes")Expect wav and flac to be much larger than mp3, opus, and aac. That gap matters when you store thousands of replies or send them to users on slow connections.
Choosing a speed
The speed parameter accepts values from 0.25 to 4.0, with 1.0 as the default. Use small adjustments. Values between about 0.9 and 1.2 sound natural for most voices. Extreme values degrade clarity and can make words run together or drag.
from openai import OpenAI
client = OpenAI()
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice="nova",
input="Please write down this confirmation code: A 7 4 9 2.",
speed=0.9,
) as response:
response.stream_to_file("code_slow.mp3")Slower speech suits codes, phone numbers, and instructions. Faster speech suits users who skim, such as screen-reader style output. Make speed a user setting where you can.
Model choice and trade-offs
tts-1is optimized for lower latency. Use it for interactive voice loops.tts-1-hdis optimized for quality. Use it for content you generate once and replay, such as narration.gpt-4o-mini-ttsadds steerable delivery throughinstructionsand a wider voice list.
A single request accepts a limited amount of text, around 4,096 characters at the time of writing. For longer text, split on sentence or paragraph boundaries and synthesize each piece separately. Splitting mid-sentence produces audible jumps in intonation.
Common errors
- A 400 error naming the voice or format. The value is misspelled or not supported by that model. Read the allowed values from the error message.
- A file that will not play. Check that the file extension matches
response_format, and that rawpcmis wrapped in a header. - Different voices between runs. You changed the voice or the model. A voice name is not guaranteed to sound identical across models.
- Choppy audio in a stream. Use a streamable format such as
mp3oropus, and avoid formats that need the whole file before playback, such asflacin some players.
Exercise
You are building a phone-style assistant. The audio goes to a browser over the network, and you also want to run a noise-level check on the same samples in Python. Which response_format would you use for each purpose, and why?
Show answer
Use mp3 or opus for delivery to the browser, because the files are small and browsers play them without extra work. Use pcm or wav for the noise-level check, because the samples are uncompressed and need no decoding. If you use pcm, wrap it in a WAV header (mono, 16-bit, 24 kHz) or read it as raw 16-bit little-endian samples.
Exercise
A teammate saves a response_format="pcm" response to reply.wav and the file will not play. What is wrong, and how do you fix it?
Show answer
Raw PCM has no header, so a player cannot tell the sample rate, sample width, or channel count. Fix it by writing the bytes through Python's wave module with 1 channel, a 2-byte sample width, and a 24000 Hz frame rate. Alternatively, request response_format="wav" and save that directly.