To convert text to speech in Python, send a transcript to a speech model and save the returned audio. This guide uses Cartesia’s Python SDK to generate a WAV file with Sonic.
You’ll need Python 3.9 or later, an internet connection, and a Cartesia account with API access. The example below targets SDK version 4.2.0.1 It calls a hosted API: your text leaves your machine. If you need offline synthesis, use a local speech engine instead.
Install the Python SDK
Create a virtual environment in your project directory:
python -m venv .venv
On macOS or Linux, activate it with:
source .venv/bin/activate
On Windows PowerShell, use:
.venv\Scripts\Activate.ps1
Then install the version used in this guide:
python -m pip install "cartesia==4.2.0"
If your system uses python3 rather than python, use that command to create the environment. Pinning the SDK keeps the example’s method names stable. When you upgrade, check the SDK release notes for changes.
Set your API key
Create an API key in the Cartesia Playground. Give it the permissions needed for text-to-speech generation. Set the key in the terminal where you’ll run Python.
On macOS or Linux:
export CARTESIA_API_KEY="your-api-key"
On Windows PowerShell:
$env:CARTESIA_API_KEY = "your-api-key"
Replace your-api-key with your own key. Treat it like a password: don’t commit it to Git, paste it into a public notebook, or put it in browser code. For a deployed application, store it in your server’s secret manager. If a key is exposed, revoke it and create a new one.
Generate and save a WAV file
Save this as speak.py:
import os
from pathlib import Path
from cartesia import Cartesia
api_key = os.environ.get("CARTESIA_API_KEY")
if not api_key:
raise SystemExit("Set CARTESIA_API_KEY before running this script.")
output_path = Path("hello.wav")
with Cartesia(api_key=api_key) as client:
response = client.tts.generate(
model_id="sonic-latest",
transcript="Hello from Python. Your first audio file is ready.",
voice="e07c00bc-4134-4eae-9ea4-1a55fb45746b",
output_format={
"container": "wav",
"encoding": "pcm_f32le",
"sample_rate": 44100,
},
)
response.write_to_file(output_path)
print(f"Saved audio to {output_path.resolve()}")
Run it from the same terminal:
python speak.py
After a successful request, open hello.wav in an audio player that supports floating-point PCM WAV. The script prints its full path, so you don’t have to guess which directory Python used. It saves audio; it does not play it automatically. Running it again overwrites hello.wav and makes another API request.
The request follows the SDK’s published usage example.1 The voice ID is the example voice from that reference. You can replace it with a voice ID available to your account.
Choose the voice, model, and audio format
The transcript is the text Sonic should speak. Start with one sentence before sending a long document. Use text you’re comfortable sending to the API, and avoid logging private transcripts in application logs.
The voice selects the speaker. Try a sentence in the voice generator, then use your chosen voice’s ID in the request. A display name is not a voice ID. If you’re using a cloned voice, make sure you have permission to use the speaker’s voice.
The example uses sonic-latest, as the SDK reference does. A model alias can change independently of your installed SDK. For repeatable production tests, choose a specific supported model ID from the model documentation and record it alongside the voice ID and test text.
The output format describes the audio file:
| Field | Value in this example | Meaning |
|---|---|---|
container |
wav |
Wraps the audio in a WAV file with a header. |
encoding |
pcm_f32le |
Stores samples as 32-bit little-endian floating-point PCM. |
sample_rate |
44100 |
Uses 44,100 audio samples per second. |
Raw PCM has no WAV header. Renaming a raw PCM file to .wav does not turn it into a WAV file. If you’re sending audio to a phone system or another service, check its required container, encoding, and sample rate before generating speech.
Fix common errors
| Symptom | What to check |
|---|---|
ModuleNotFoundError: No module named 'cartesia' |
Activate the environment where you installed the SDK. Run python -m pip show cartesia with the same Python interpreter that runs the script. |
Set CARTESIA_API_KEY before running this script. |
Set the environment variable in the current terminal, then rerun the script. An editor or notebook may use a different environment. |
| Authentication or permission error | Check that the key is active, belongs to the intended account, and has the required permissions. Never paste the key into an error report. |
| An error about the model, voice, or output format | Check the current API reference and confirm the voice is available to your account. Copy IDs exactly. |
| Rate-limit error | Check your account limits and reduce request concurrency. Avoid an immediate retry loop. |
AttributeError involving generate |
Check the installed SDK version. Older examples may use client.tts.bytes; this guide uses client.tts.generate in version 4.2.0. |
| The file exists but won’t play | Confirm the request uses container="wav" and that your player supports floating-point PCM. Check that the file is nonempty. |
When you ask for help, include your Python and SDK versions, the status code, and any request ID returned with the error. Remove API keys and private text first.
When to use streaming instead
Saving a WAV file is useful for narration, voiceovers, and checking an integration. A conversational application may need to play audio before a full response is ready, or accept text as an LLM generates it.
For that case, install WebSocket support in the same environment:
python -m pip install "cartesia[websockets]==4.2.0"
Then start with the SDK’s streaming-input WebSocket example.1 You’ll also need audio playback, buffering, and interruption handling. Writing arriving chunks to disk alone does not make the application speak in real time.
Once the short example works, replace the transcript with a sentence from your application. Listen for names, numbers, and abbreviations before generating a larger batch. Check API pricing and keep the model and voice IDs with your test results.
Footnotes
-
Cartesia, Python SDK 4.2.0 on PyPI and SDK usage reference, checked September 13, 2026. ↩ ↩2 ↩3