def tts_sse_with_match(client: Cartesia) -> None:
"""SSE streaming using match statement."""
stream = client.tts.generate_sse(
model_id="sonic-3",
transcript="Hello, world!",
voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
output_format={"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100},
)
import datetime
filename = f"tts_sse_with_match_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.pcm"
with open(filename, "wb") as f:
for event in stream:
if event.type == "chunk":
# Audio chunk - event.audio contains bytes
if event.audio:
f.write(event.audio)
process_audio(event.audio)
elif event.type == "timestamps":
# Word timestamps - event.word_timestamps
process_timestamps(event.word_timestamps)
elif event.type == "done":
# Stream complete
break
elif event.type == "error":
# Error occurred
raise Exception(event.error)
print(f"Saved audio to {filename}")
print(f"Play with: ffplay -f f32le -ar 44100 {filename}")
Run this example
cd cartesia-python
CARTESIA_API_KEY=YOUR_KEY python3 examples/examples.py tts_sse_with_match