Skip to main content
The speech endpoint converts text to audio. Confirm that API_MODEL supports speech synthesis and set a compatible API_VOICE. Chat models and voice names are not interchangeable.

Save an MP3

Configure API_BASE_URL (including /v1), API_KEY, and API_MODEL using the Python SDK guide, then set API_VOICE. Save as speech.py and run python speech.py. It writes speech.mp3 in the current directory without overwriting an existing file. The example requests response_format: mp3, reads audio bytes, and caps the output at 16 MiB (an example-only limit). It checks HTTP status and Content-Type to avoid treating JSON errors as audio; it does not fully decode or validate the audio.

Formats and streaming boundaries

input is text, voice selects a voice, and instructions provides style guidance on supporting models. Speed, input length, languages, and output formats depend on the model. Changing an extension does not transcode audio. PCM also requires the correct sample rate, bit depth, and channel count; it is not a WAV file. SDK with_streaming_response reads HTTP audio bytes in chunks. It is not SSE or a bidirectional live voice session. Use stream_format: sse only with explicit channel support and a matching event parser. Microphone interaction, WebRTC, and Realtime sessions are outside this file-synthesis workflow.

Handle failures

For non-2xx responses, check the model, voice, parameters, permissions, and logs. Do not treat interrupted audio as a complete result; this example collects the full response before writing. Automatic retries are disabled to avoid duplicate synthesis after an ambiguous failure. Clearly label synthesized speech in your product; OpenAI explicitly requires disclosure, as described in its text-to-speech guide. 简体中文