Artificial AnalysisRanked #1 in Speech Arena

Text to speech API, first audio in under 90ms

Install one package and a single request saves a WAV file. Stream over WebSocket in any of 44 languages, and speech starts while your LLM is still writing.
speech.py
audio = client.tts.generate(
    transcript="Hello, world.",
    model_id="sonic-3.6",
    voice=voice_id,
    output_format=wav_format,
)
audio.write_to_file("speech.wav")

speech.wav

Full example

Your first text-to-speech request

Install the SDK

Use Python 3.9 or later in a virtual environment.

Terminal
python -m pip install --upgrade cartesia

Set your API key

Create a key in Playground. Replace the placeholder below and keep your key on the server.

macOS / Linux
export CARTESIA_API_KEY="your-api-key"

Using PowerShell?$env:CARTESIA_API_KEY="your-api-key"

Generate your first recording

Save this example as speech.py. Run it from your terminal, then open speech.wav to listen.

Terminal
python speech.py

Change the transcript or choose a voice ID from Playground to hear a different result.

Output file
speech.wav
Audio format
44.1 kHz, 16-bit PCM
speech.py
import os
from cartesia import Cartesia

with Cartesia(api_key=os.environ["CARTESIA_API_KEY"]) as client:
    audio = client.tts.generate(
        model_id="sonic-3.6",
        transcript="Hello from your Python application.",
        voice="db6b0ed5-d5d3-463d-ae85-518a07d3c2b4",
        output_format={
            "container": "wav",
            "encoding": "pcm_s16le",
            "sample_rate": 44100,
        },
    )
    audio.write_to_file("speech.wav")

Choose how audio reaches your app

The right transport depends on when your text is ready and how you plan to play the response.

Save a recording

Transport
HTTP
Output
WAV or MP3

Convert a complete script to audio and save it for later playback. The example above produces a WAV file with a header that audio players can read.

Read the audio output reference

Speak as text arrives

Transport
WebSocket
Output
Raw audio chunks

Send text fragments as your LLM writes and receive audio chunks as Sonic generates them. Forward those chunks to a player configured for the requested audio format.

Build a streaming example

Stream audio from a complete script

Already have all your text? Use with_streaming_response to read the HTTP response in chunks.

Keep your key on the server

A Python backend can own the request while your web app, mobile app, or phone system owns playback.

01

Your Python server

Read the API key from your environment. Choose the voice, model, and audio settings for each request.

02

Sonic

Convert the text into speech. Receive an audio response or keep a WebSocket open for incremental input.

03

Your application

Save the recording or pass audio to your player. Match its encoding and sample rate to the response.

From a script to a production service

What to handle before real users hear it.

Fit your Python stack

Use the synchronous client for scripts and background jobs. Use AsyncCartesia in an async service such as FastAPI. Close the client when its work is finished, then pass the audio to your storage or playback service.

Test the full listening experience

Set request timeouts and handle rate limits. Test realistic scripts with the voice you will ship. For conversations, measure time to audible speech and make sure interruptions stop queued playback. Your network and player affect what a listener hears.

Enterprise-grade security.From Cloud to Local.

  • HIPAA compliant badge

    HIPAA compliant

  • SOC 2 Type 2 badge

    SOC 2 Type 2

  • GDPR badge

    GDPR

  • PCI badge

    PCI

Python text-to-speech questions

How do I convert text to speech in Python?

Install cartesia, set CARTESIA_API_KEY in your server environment, and create a Cartesia client. Call client.tts.generate with your transcript, model, voice ID, and output format, then save the response with write_to_file. The example on this page produces speech.wav. See the Python examples for complete requests.

Which Python version and SDK do I need?

The official SDK requires Python 3.9 or later. Install it with python -m pip install --upgrade cartesia. For WebSocket support, install python -m pip install "cartesia[websockets]". Check your installed package version against the SDK documentation when adapting an older example.

Can I save generated speech as WAV or MP3?

Yes. The TTS endpoint supports WAV, MP3, and raw audio output. Choose the container and its supported settings in output_format before generating speech. Use WAV for the example on this page; choose MP3 when your application needs that format. Changing a filename extension alone does not convert the audio.

How do I stream an LLM response into speech with Python?

Use a WebSocket when your application receives text a piece at a time. Send those text chunks through a shared generation context and consume the returned audio chunks as they arrive. Your application still needs to buffer and play that audio. The WebSocket API explains continuation and cancellation for conversational applications.

Should I use HTTP or WebSockets for text-to-speech?

Use HTTP when the transcript is already available, such as a complete narration or notification. An HTTP response can deliver audio progressively too. Use WebSockets when you need to send text incrementally or manage a continuing conversation. Streaming input and streaming output are separate choices; saving a file is not the only way to consume an HTTP response.

Can I use Cartesia with async Python or FastAPI?

Yes. Use AsyncCartesia and await its API calls in an async application. The SDK's async examples show generation, file output, and streaming. Connect the returned audio to your application's response or player, and close the client when its lifecycle ends.

Where should I store my Cartesia API key?

Keep your long-lived key in a server environment variable or deployment secret manager. Do not commit it or send it to browser code. If the browser needs a direct connection, have your backend create a scoped, short-lived token through the access-token API.

How do I choose a voice and language for Python TTS?

Preview a voice in the Playground and pass its ID in the request. Set language or locale for your transcript, but not both. Test names, numbers, and abbreviations from your own scripts. See the request reference for language and voice settings rather than assuming every voice has the same accent support.

Which Sonic model ID should I use in production?

Choose a model from the current Sonic documentation and test it with your application. The sonic-3.6 ID receives stable snapshot updates. A published dated snapshot keeps model behavior fixed while you evaluate a newer release. Record the model ID alongside your tests so you can compare results after an upgrade.

Why does raw PCM need special playback settings?

Raw PCM does not contain a file header describing how to play it. The player needs the sample rate and encoding used in your request. A mismatch can produce noise, silence, or speech at the wrong speed. Start with a WAV output to check the generated speech separately from your streaming player, then test the raw-audio playback path.

What should I handle before using Python TTS in production?

Handle authentication failures, rate limits, network errors, and timeouts. Configure the SDK's retries and timeouts to fit your application. Test interrupted playback and avoid replaying queued audio after the user changes direction. Measure from text becoming available to audible speech, including your network and playback buffer.

Get started today

Talk to an expert.

Connect with a member of our team and learn how Cartesia can help you build world-class voice experiences.

Contact Sales

Start building.

Access our models via API and bring a voice agent into production in minutes.

Try Cartesia