Skip to content
,

OpenAI Text-to-Speech API: Python Guide, Voices, Pricing (2026)

13โ€“19 minutes
Woman in a white lab coat in a home office holding a tablet with an OPENAI API card, hook 13 voices ends Jan 2027

OpenAI’s text-to-speech API turns any text into natural audio with one API call. You pick a model, a voice and an output format, and you get back an MP3, WAV or other audio file.

There is one big catch in late 2026. OpenAI has deprecated all three Speech API models, and they shut down on January 6, 2027. This guide shows how to use the API today and how to move to the replacement.

TLDR

  • Endpoint: POST /v1/audio/speech with model, voice and input.
  • Models: gpt-4o-mini-tts (steerable), tts-1 (fast) and tts-1-hd (higher quality). All three shut down on January 6, 2027.
  • Replacement: OpenAI recommends gpt-realtime-2.1-mini through the Realtime API, which needs a WebSocket instead of one HTTP call.
  • Voices: 13 built-in voices. OpenAI recommends marin or cedar for the best quality.
  • Limit: 4,096 characters per request, so split long text into chunks.
  • Price: tts-1 costs $15 per 1M characters, tts-1-hd $30, and gpt-4o-mini-tts $0.60 per 1M text tokens plus $12 per 1M audio tokens.
  • Policy: you must tell listeners the voice is AI-generated.

What the OpenAI Text-to-Speech API Is

The Speech endpoint (/v1/audio/speech) takes text and returns spoken audio. It is a simple request and response API: send text, get a file back.

OpenAI lists these common uses in its text-to-speech guide:

  • Narrating content: turn blog posts, docs or lessons into audio versions.
  • Multilingual audio: produce spoken audio in many languages from text.
  • Realtime output: stream speech so playback starts before the full file is ready.

Use the Speech API when you already have the exact text to read. If you need a voice agent that listens and replies in a live conversation, look at the Realtime API or the newer GPT-Live 1.1 API instead.

The January 2027 Shutdown: What It Means

OpenAI’s deprecations page lists a notice date of October 1, 2026 for every Speech API model. The shutdown date is January 6, 2027.

Model Notice date Shutdown date Recommended replacement
tts-1 Oct 1, 2026 Jan 6, 2027 gpt-realtime-2.1-mini
tts-1-hd Oct 1, 2026 Jan 6, 2027 gpt-realtime-2.1-mini
gpt-4o-mini-tts (plus the 2025-03-20 and 2025-12-15 snapshots) Oct 1, 2026 Jan 6, 2027 gpt-realtime-2.1-mini

Warning: the replacement is not supported on /v1/audio/speech. OpenAI’s guide says moving to it is a change in workflow, not a simple model swap. Your existing code keeps working only until the shutdown date.

So what should you do today? Here is a simple plan:

  • Short-lived scripts or prototypes: the Speech API is still the easiest option until January 6, 2027.
  • Production apps: build new features on the Realtime API now, and keep a small wrapper so you can swap the backend in one place.
  • Pre-generated audio: if you create narration files once, generate them before the shutdown and store them. Saved files keep working.

TTS Models and Voices

Three models work on the Speech endpoint. They differ in quality, speed and whether you can steer the voice with a prompt.

Model Best for Supports instructions Voices Price
gpt-4o-mini-tts Steerable, expressive speech Yes All 13 $0.60 / 1M text tokens + $12 / 1M audio tokens
tts-1 Lower latency, lower quality No 9 $15 / 1M characters
tts-1-hd Higher quality, higher latency No 9 $30 / 1M characters

The gpt-4o-mini-tts alias points to the gpt-4o-mini-tts-2025-12-15 snapshot by default. You can pin that snapshot name if you want stable behaviour.

The 13 built-in voices

The current voice list is: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer, verse, marin and cedar. OpenAI recommends marin or cedar for the best quality.

  • gpt-4o-mini-tts: all 13 voices.
  • tts-1 and tts-1-hd: alloy, ash, coral, echo, fable, onyx, nova, sage and shimmer only.
  • Language: the voices are tuned for English, but they speak many other languages. Write the input text in the language you want to hear.

Note: the Speech endpoint also accepts a custom voice object such as {"id": "voice_1234"}. Custom voices must be created from a speaker’s consent recording and audio sample. Voices created from a text prompt work only in GPT-Live.

Prerequisites and Setup

You need three things before you start:

  1. Create a project folder. Run mkdir tts-demo and then cd tts-demo.
  2. Make a virtual environment. Run python -m venv .venv, then activate it with source .venv/bin/activate (on Windows, run .venv\Scripts\activate).
  3. Install the SDK. Run pip install "openai[voice-helpers,realtime]". The voice-helpers extra adds speaker playback, and realtime adds WebSocket support for Example 5. This guide was checked against openai 3.60.0 (released November 26, 2026).
  4. Set your key as an environment variable. Run export OPENAI_API_KEY="sk-..." on macOS or Linux, or setx OPENAI_API_KEY "sk-..." on Windows. Never paste the key into your code.
  5. Run a test. Save Example 1 below as tts.py and run python tts.py. You should get a welcome.mp3 file.

New to the SDK in general? Our OpenAI API Python tutorial covers clients, errors and retries in more depth.

Example 1: Save Speech to an MP3 File

This is the smallest useful script. It sends one sentence and writes the audio to welcome.mp3. MP3 is the default format, so you don’t need to set it.

from pathlib import Path
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from your environment

speech_file = Path(__file__).parent / "welcome.mp3"

with client.audio.speech.with_streaming_response.create(
    model="gpt-4o-mini-tts",
    voice="marin",
    input="Welcome to FreakyJolly. Today we turn text into speech with Python.",
) as response:
    response.stream_to_file(speech_file)

print(f"Saved {speech_file}")

The with_streaming_response wrapper writes the audio to disk as it arrives. That keeps memory low, even for long files.

Here is the same request with curl. It is handy for testing your key before writing any Python.

curl https://api.openai.com/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini-tts",
    "input": "Hello from the OpenAI Speech API.",
    "voice": "marin",
    "instructions": "Speak in a cheerful and positive tone.",
    "response_format": "mp3"
  }' \
  --output hello.mp3

Example 2: Steer Tone With Instructions

The instructions parameter is what makes gpt-4o-mini-tts special. You describe how the voice should sound in plain English, and the model follows it.

OpenAI says you can control these aspects with instructions:

  • Accent and impressions: for example, “light Irish accent”.
  • Emotion and intonation: calm, excited, sympathetic or serious.
  • Speed and tone: slow and soothing, or quick and punchy.
  • Whispering: soft, quiet delivery for scripts like bedtime stories.

This script reads the same sentence in three styles so you can compare them:

from openai import OpenAI

client = OpenAI()

styles = {
    "calm": "Speak slowly and calmly, like a meditation guide. Soft, warm tone.",
    "news": "Sound like a confident news anchor. Clear, neutral, steady pace.",
    "excited": "Sound upbeat and excited, like announcing a product launch.",
}

text = "Your order has shipped and will arrive on Friday."

for name, style in styles.items():
    with client.audio.speech.with_streaming_response.create(
        model="gpt-4o-mini-tts",
        voice="cedar",
        input=text,
        instructions=style,
        speed=1.0,
    ) as response:
        response.stream_to_file(f"order_{name}.mp3")
    print("Saved", f"order_{name}.mp3")

Tip: keep instructions short and concrete. Describe the speaker (“a patient teacher”), the pace and the mood. Leave the actual words in input, because instructions shape delivery, not content.

A few rules to remember:

  • Length: instructions can be up to 4,096 characters.
  • Model support: instructions do not work with tts-1 or tts-1-hd.
  • Speed: the speed parameter accepts 0.25 to 4.0, and the default is 1.0.

Example 3: Stream Audio as It Is Generated

The Speech API uses chunked transfer encoding. That means audio can start playing before the whole file has been generated.

This async example plays speech straight through your speakers with the SDK’s LocalAudioPlayer helper. It asks for pcm, because OpenAI recommends wav or pcm for the fastest response.

import asyncio
from openai import AsyncOpenAI
from openai.helpers import LocalAudioPlayer

client = AsyncOpenAI()

async def main() -> None:
    async with client.audio.speech.with_streaming_response.create(
        model="gpt-4o-mini-tts",
        voice="coral",
        input="Streaming lets playback start before the whole file is ready.",
        instructions="Friendly and clear, medium pace.",
        response_format="pcm",  # raw 24 kHz audio, fastest to start
    ) as response:
        await LocalAudioPlayer().play(response)

asyncio.run(main())

If you only want a file, Example 1 already streams to disk. To pipe live audio on the command line, you can send the curl output to a player such as ffplay.

The API also has a stream_format parameter with two values: audio (the default, raw audio bytes) and sse (server-sent events). The sse option does not work with tts-1 or tts-1-hd.

Output Formats Compared

Set response_format to choose the file type. The default is mp3.

Format What it is good for Notes
mp3 General use, podcasts, downloads Default format
opus Internet streaming and calls Low latency
aac Digital audio compression Preferred by many apps and devices
flac Archiving Lossless compression
wav Low-latency playback, editing Uncompressed, has a header
pcm Custom audio pipelines Raw 24 kHz, 16-bit signed little-endian samples, no header

Pick mp3 if you are unsure. Pick pcm when you need to join chunks, as in the next example.

Example 4: Split Long Text Past the Character Limit

Each request accepts at most 4,096 characters of input. The gpt-4o-mini-tts model page also lists a maximum input of 2,000 tokens, so very dense text can hit that cap first.

The fix is to split your text at sentence ends, convert each chunk, and join the audio. Follow these steps:

  1. Split the text. Break it at sentence boundaries into chunks of about 3,000 characters.
  2. Keep the settings fixed. Use the same voice and instructions for every chunk, so the narration sounds consistent.
  3. Request raw PCM. PCM has no header, so chunks can be glued together cleanly.
  4. Write one WAV file. Python’s built-in wave module adds the header for 24 kHz, 16-bit mono audio.
import re
import wave
from openai import OpenAI

client = OpenAI()
MAX_CHARS = 3000  # stays under the 4,096 character cap and the 2,000 token cap


def split_text(text: str, max_chars: int = MAX_CHARS) -> list[str]:
    """Split on sentence ends so each chunk stays under max_chars."""
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    chunks, current = [], ""
    for sentence in sentences:
        if len(sentence) > max_chars:  # very long sentence: hard cut
            if current:
                chunks.append(current)
                current = ""
            for i in range(0, len(sentence), max_chars):
                chunks.append(sentence[i:i + max_chars])
            continue
        if len(current) + len(sentence) + 1 > max_chars:
            chunks.append(current)
            current = sentence
        else:
            current = f"{current} {sentence}".strip()
    if current:
        chunks.append(current)
    return chunks


def text_to_wav(text: str, out_path: str, voice: str = "marin") -> None:
    style = "Narrate like an audiobook reader. Warm, even pace."
    with wave.open(out_path, "wb") as wav:
        wav.setnchannels(1)      # mono
        wav.setsampwidth(2)      # 16-bit
        wav.setframerate(24000)  # 24 kHz
        for n, chunk in enumerate(split_text(text), start=1):
            audio = client.audio.speech.create(
                model="gpt-4o-mini-tts",
                voice=voice,          # keep the same voice for every chunk
                input=chunk,
                instructions=style,   # and the same style
                response_format="pcm",
            )
            wav.writeframes(audio.content)
            print(f"Chunk {n} done ({len(chunk)} characters)")


if __name__ == "__main__":
    long_text = open("article.txt", encoding="utf-8").read()
    text_to_wav(long_text, "article.wav")

Tip: want an MP3 at the end? Convert the WAV with a tool like ffmpeg -i article.wav article.mp3. Joining MP3 chunks directly can leave small gaps or glitches between files.

Example 5: Move to gpt-realtime-2.1-mini

OpenAI’s named replacement is gpt-realtime-2.1-mini, released on July 6, 2026. It is a voice model on the Realtime API (/v1/realtime) that accepts text and returns audio over WebRTC, WebSocket or SIP.

It is a conversational model, not a pure reader. So you give it a system instruction that tells it to read the user’s text aloud word for word. The script below connects over WebSocket, sends text and saves the audio deltas to a WAV file.

import asyncio
import base64
import wave
from openai import AsyncOpenAI

client = AsyncOpenAI()

READER = (
    "You are a text-to-speech reader. Read the user's text aloud exactly as "
    "written, word for word. Do not answer it, comment on it or add anything."
)

async def speak(text: str, out_path: str = "realtime.wav") -> None:
    audio = bytearray()
    async with client.realtime.connect(model="gpt-realtime-2.1-mini") as conn:
        await conn.session.update(session={
            "type": "realtime",
            "instructions": READER,
            "output_modalities": ["audio"],
            "audio": {"output": {
                "voice": "marin",
                "format": {"type": "audio/pcm", "rate": 24000},
            }},
        })
        await conn.conversation.item.create(item={
            "type": "message",
            "role": "user",
            "content": [{"type": "input_text", "text": text}],
        })
        await conn.response.create()

        async for event in conn:
            if event.type == "response.output_audio.delta":
                audio.extend(base64.b64decode(event.delta))
            elif event.type == "error":
                print("Error:", event.error.message)
                break
            elif event.type == "response.done":
                break

    with wave.open(out_path, "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(24000)
        wav.writeframes(bytes(audio))
    print("Saved", out_path)

asyncio.run(speak("This audio came from the Realtime API, not the Speech endpoint."))

Key differences from the Speech API:

  • Connection: a WebSocket session instead of one HTTP request.
  • Audio arrives as events: each response.output_audio.delta event carries base64-encoded audio.
  • Errors don’t raise: the SDK sends an error event and keeps the connection open, so you must check for it yourself.
  • Voices: the Realtime voice list is alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin and cedar (fable, onyx and nova are not in it).
  • Exact wording isn’t guaranteed: test it with your own scripts, because a conversational model may still change words.

For full session options, turn detection and voice agents, see our OpenAI Realtime API guide.

Usage Policy: Disclose AI Voices

OpenAI’s usage policies require you to give end users a clear disclosure that the voice is AI-generated and not a human. This applies to every app that plays TTS audio to people.

Simple ways to meet that rule:

  • Podcasts and narrated posts: add a line like “This audio was generated with an AI voice” at the start or in the player.
  • Phone and support bots: say it is an AI assistant in the first sentence of the call.
  • Apps and games: label AI voices in the settings screen or credits.

OpenAI also says its TTS models are limited to artificial, preset voices, which it monitors. Never use TTS to impersonate a real person without their consent.

Pricing and a Worked Cost Example

The Speech models are priced in two different ways. The older models charge per character, while gpt-4o-mini-tts charges per token.

Model Input price Output price
tts-1 $15 per 1M characters
tts-1-hd $30 per 1M characters
gpt-4o-mini-tts $0.60 per 1M text tokens (instructions count too) $12 per 1M audio tokens
gpt-realtime-2.1-mini (replacement) $0.60 per 1M text tokens $20 per 1M audio tokens

Worked example: narrating a 1,000-word blog post

Assume a 1,000-word post is about 6,000 characters including spaces. At a normal reading pace of about 150 words per minute, that is roughly 6 to 7 minutes of audio.

  • tts-1: 6,000 / 1,000,000 x $15 = $0.09.
  • tts-1-hd: 6,000 / 1,000,000 x $30 = $0.18.
  • gpt-4o-mini-tts: the text input is tiny (about 1,300 tokens, well under one cent). Most of the cost is audio output. Developers on the OpenAI forum report roughly 1.5 cents per minute, so expect about $0.10.

So 100 posts a month would cost about $9 with tts-1 or $18 with tts-1-hd. For token-priced models, check the Usage dashboard after a few test runs, because it splits input text and output audio tokens.

Note: one forum user reported being billed for trailing silence in a generated file. Listen to a few outputs and compare durations before you scale up a batch job.

Limits and Rate Limits

Limit Value
Input text 4,096 characters per request
gpt-4o-mini-tts max input 2,000 tokens
Instructions 4,096 characters (not on tts-1 or tts-1-hd)
Speed 0.25 to 4.0 (default 1.0)
gpt-4o-mini-tts rate limits Build 2,000 RPM / 150,000 TPM, Launch 10,000 RPM / 2M TPM, Grow 10,000 RPM / 8M TPM
tts-1 rate limits Free 3 RPM / 200 RPD, Build 2,500 RPM, Launch 7,500 RPM, Grow 10,000 RPM
tts-1-hd rate limits Build 2,500 RPM, Launch 7,500 RPM, Grow 10,000 RPM
gpt-realtime-2.1-mini 128,000 token context, 32,000 max output; Build 400 RPM / 200,000 TPM

Your tier rises automatically as you use and spend more on the API. Our API rate limits and tiers guide explains how tiers work.

Troubleshooting: Common Errors and Fixes

Error Likely cause Fix
400, “string too long” on input Text is over 4,096 characters Split the text with Example 4
400 error mentioning instructions or sse Using instructions or SSE streaming with tts-1 or tts-1-hd Switch to gpt-4o-mini-tts or remove the parameter
400 invalid value for voice A newer voice (like marin) sent to tts-1 or tts-1-hd Use one of the 9 older voices, or use gpt-4o-mini-tts
401 “Incorrect API key provided” Wrong, revoked or badly pasted key Check OPENAI_API_KEY for spaces, or create a new key
403 “Country, region, or territory not supported” Calling from an unsupported location Check OpenAI’s supported countries list
429 “Rate limit reached for requests” Too many requests per minute Slow down and wait for the Retry-After time
429 “Credit balance exhausted” No prepaid credits left Add credits; retrying won’t help
500 “The server had an error while processing your request” OpenAI server problem Retry after a short wait and check the status page
503 “Model temporarily overloaded” Not enough capacity right now Retry after the Retry-After time
“You need to install openai[realtime]” WebSocket extra is missing Run pip install "openai[realtime]"
Model not found after January 6, 2027 The Speech models have shut down Move to gpt-realtime-2.1-mini (Example 5)

Two more problems that don’t show as errors:

  • Audio sounds like static: you saved raw pcm with an .mp3 or .wav name. Wrap PCM in a WAV header as in Example 4.
  • Voice changes between chunks: keep the same model, voice and instructions for every chunk.

For a deeper list of API errors, see our OpenAI API errors fix guide.

Frequently Asked Questions

Is the OpenAI text-to-speech API being shut down?

Yes. The tts-1, tts-1-hd and gpt-4o-mini-tts models shut down on January 6, 2027. OpenAI recommends gpt-realtime-2.1-mini on the Realtime API as the replacement.

Which OpenAI TTS voice sounds the best?

OpenAI recommends marin or cedar for the best quality. Both work with gpt-4o-mini-tts and the Realtime models, but not with tts-1 or tts-1-hd.

How do I change the tone or emotion of the voice?

Use the instructions parameter with gpt-4o-mini-tts, for example “speak calmly like a meditation guide”. It does not work with tts-1 or tts-1-hd.

What is the maximum text length per request?

Each request accepts up to 4,096 characters, and gpt-4o-mini-tts also lists a 2,000 token input cap. Split longer text at sentence ends and join the audio.

How much does OpenAI text-to-speech cost?

tts-1 costs $15 per 1M characters and tts-1-hd costs $30. gpt-4o-mini-tts costs $0.60 per 1M text tokens plus $12 per 1M audio output tokens.

Do I have to tell people the voice is AI?

Yes. OpenAI’s usage policies require a clear disclosure to end users that the TTS voice is AI-generated and not a human.

Can I clone my own voice with the API?

OpenAI supports approved custom voices created from a speaker’s consent recording and an audio sample. You then pass the voice ID, such as {“id”: “voice_1234”}, in the voice parameter.

Does the API support languages other than English?

Yes. The models follow Whisper’s language support, including Spanish, French, German, Japanese, Chinese, Hindi and Arabic. Write the input in the language you want spoken.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a white lab coat in a home office holding a tablet with an OPENAI API card, hook 13 voices ends Jan 2027