Skip to main content
def tts_websocket_flushing(client: Cartesia) -> None:
    """Demonstrates manual flushing to separate audio from different transcripts."""
    transcripts = ["Stay hungry, ", "stay foolish."]
    output_format = {"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100}

    with client.tts.websocket_connect() as connection:
        ctx = connection.context(
            model_id="sonic-3",
            voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
            output_format=output_format
        )  # Auto-generates context_id

        # 1. Send first transcript
        print("Sending first transcript...")
        ctx.push(transcripts[0])

        # 2. Flush! This forces all buffered audio for the first transcript to be generated
        # and increments the flush_id counter on the server.
        print("Flushing...")
        ctx.flush()

        # 3. Send second transcript
        print("Sending second transcript...")
        ctx.push(transcripts[1])

        ctx.no_more_inputs()

        import datetime
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')

        # We'll save audio to separate files based on flush_id
        files: dict[int, IO[bytes]] = {}

        for response in ctx.receive():
            # Log every response, but redact audio data to avoid swamping the console.
            loggable = {k: ("[...]" if k == "data" else v) for k, v in response.model_dump().items()}
            print(f"Event: {loggable}")

            if response.type == "chunk" and response.audio:
                # Get flush_id from response (defaults to 0 if not present)
                flush_id = response.flush_id or 0

                if flush_id not in files:
                    filename = f"tts_flush_{flush_id}_{timestamp}.pcm"
                    files[flush_id] = open(filename, "wb")

                files[flush_id].write(response.audio)

        # Close all open files
        for f in files.values():
            f.close()

        print("\nFinished.")
        print("You can play the generated audio files with these commands:")
        for flush_id, f in files.items():
            print(f"  Flush ID {flush_id}: ffplay -f f32le -ar 44100 {f.name}")
From cartesia-python/examples/examples.py:255

Run this example

cd cartesia-python
CARTESIA_API_KEY=YOUR_KEY python3 examples/examples.py tts_websocket_flushing