> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cartesia.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SSE with Word Timestamps

> SSE streaming with word timestamps.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    def tts_sse_with_timestamps(client: Cartesia) -> None:
        """SSE streaming with word timestamps."""
        stream = client.tts.generate_sse(
            model_id="sonic-latest",
            transcript="Hello, world!",
            voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
            output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 44100},
            language="en",
            add_timestamps=True,
        )

        import datetime

        filename = f"tts_sse_with_timestamps_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.pcm"

        with open(filename, "wb") as f:
            for event in stream:
                if event.type == "timestamps":
                    wt = event.word_timestamps
                    if wt:
                        print(f"Words: {wt.words}, Starts: {wt.start}, Ends: {wt.end}")
                elif event.type == "chunk":
                    if event.audio:
                        f.write(event.audio)
                elif event.type == "done":
                    break
                elif event.type == "error":
                    raise Exception(f"{event.title}: {event.message}")

        print(f"Saved audio to {filename}")
        print(f"Play with: ffplay -f s16le -ar 44100 {filename}")
    ```

    From [cartesia-python/examples/examples.py:93](https://github.com/cartesia-ai/cartesia-python/blob/v3.2.0/examples/examples.py#L93)
  </Tab>

  <Tab title="Python (Async)">
    ```python theme={null}
    async def tts_sse_with_timestamps_async(client: AsyncCartesia) -> None:
        """Async SSE streaming with timestamps."""
        import datetime

        stream = await client.tts.generate_sse(
            model_id="sonic-latest",
            transcript="Hello, world!",
            voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
            output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 44100},
            language="en",
            add_timestamps=True,
        )

        filename = f"tts_sse_timestamps_async_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.pcm"

        with open(filename, "wb") as f:
            async for event in stream:
                if event.type == "timestamps":
                    wt = event.word_timestamps
                    if wt:
                        print(f"Words: {wt.words}, Starts: {wt.start}, Ends: {wt.end}")
                elif event.type == "chunk":
                    if event.audio:
                        f.write(event.audio)
                elif event.type == "done":
                    break
                elif event.type == "error":
                    raise Exception(f"{event.title}: {event.message}")

        print(f"Saved audio to {filename}")
        print(f"Play with: ffplay -f s16le -ar 44100 {filename}")
    ```

    From [cartesia-python/examples/async\_examples.py:85](https://github.com/cartesia-ai/cartesia-python/blob/v3.2.0/examples/async_examples.py#L85)
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    async function ttsSSEWithTimestamps(client: Cartesia): Promise<void> {
      const stream = await client.tts.generateSSE({
        model_id: 'sonic-latest',
        transcript: 'Hello, world!',
        voice: { mode: 'id', id: '6ccbfb76-1fc6-48f7-b71d-91ac6298247b' },
        output_format: { container: 'raw', encoding: 'pcm_f32le', sample_rate: 44100 },
        language: 'en',
        add_timestamps: true,
      });

      const filename = `tts_sse_timestamps_${timestamp()}.pcm`;
      const file = fs.createWriteStream(filename);

      try {
        for await (const event of stream) {
          if (event.type === 'timestamps') {
            const wt = event.word_timestamps;
            if (wt) {
              console.log(`Words: ${wt.words}, Starts: ${wt.start}, Ends: ${wt.end}`);
            }
          } else if (event.type === 'chunk') {
            file.write(Buffer.from(event.data, 'base64'));
          } else if (event.type === 'done') {
            break;
          } else if (event.type === 'error') {
            throw new Error(`${event.title}: ${event.message}`);
          }
        }
      } finally {
        file.end();
      }

      console.log(`Saved audio to ${filename}`);
      console.log(`Play with: ffplay -f f32le -ar 44100 ${filename}`);
    }
    ```

    From [cartesia-js/examples/node\_examples.ts:495](https://github.com/cartesia-ai/cartesia-js/blob/v3.2.0/examples/node_examples.ts#L495)
  </Tab>
</Tabs>

## Run this example

<Tabs>
  <Tab title="Python">
    ```sh theme={null}
    git clone --branch v3.2.0 https://github.com/cartesia-ai/cartesia-python
    cd cartesia-python
    uv sync
    CARTESIA_API_KEY=YOUR_KEY uv run examples/examples.py tts_sse_with_timestamps
    ```
  </Tab>

  <Tab title="Python (Async)">
    ```sh theme={null}
    git clone --branch v3.2.0 https://github.com/cartesia-ai/cartesia-python
    cd cartesia-python
    uv sync
    CARTESIA_API_KEY=YOUR_KEY uv run examples/async_examples.py tts_sse_with_timestamps_async
    ```
  </Tab>

  <Tab title="TypeScript">
    ```sh theme={null}
    git clone --branch v3.2.0 https://github.com/cartesia-ai/cartesia-js
    cd cartesia-js
    pnpm i
    CARTESIA_API_KEY=YOUR_KEY pnpm tsn examples/node_examples.ts ttsSSEWithTimestamps
    ```
  </Tab>
</Tabs>
