> ## 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.

# WebSocket Emotion Control

> Demonstrates changing emotion mid-stream using generation_config.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    def tts_websocket_emotion(client: Cartesia) -> None:
        """Demonstrates changing emotion mid-stream using generation_config."""
        with client.tts.websocket_connect() as ws:
            ctx = ws.context(
                model_id="sonic-latest",
                voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
                output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 44100},
                language="en",
            )

            print("Sending neutral text...")
            ctx.push("Well maybe if you just ")

            print("Sending angry text...")
            ctx.push("loosen up a little!", generation_config={"emotion": "angry"})

            ctx.no_more_inputs()

            import datetime

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

            with open(filename, "wb") as f:
                for response in ctx.receive():
                    if response.type == "chunk" and response.audio:
                        f.write(response.audio)
                    elif response.type == "error":
                        print(f"error: {response.message or response.title}")

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

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

  <Tab title="Python (Async)">
    ```python theme={null}
    async def tts_websocket_emotion_async(client: AsyncCartesia) -> None:
        """Async emotion changing example."""

        async with client.tts.websocket_connect() as ws:
            ctx = ws.context(
                model_id="sonic-latest",
                voice={"mode": "id", "id": "6ccbfb76-1fc6-48f7-b71d-91ac6298247b"},
                output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 44100},
                language="en",
            )

            print("Sending neutral text...")
            await ctx.push("Well maybe if you just ")

            print("Sending angry text...")
            await ctx.push("loosen up a little!", generation_config={"emotion": "angry"})

            await ctx.no_more_inputs()

            import datetime

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

            with open(filename, "wb") as f:
                async for response in ctx.receive():
                    if response.type == "chunk" and response.audio:
                        f.write(response.audio)
                    elif response.type == "error":
                        print(f"error: {response.message or response.title}")

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

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

  <Tab title="TypeScript">
    ```typescript theme={null}
    async function ttsWebsocketEmotion(client: Cartesia): Promise<void> {
      const ws = await client.tts.websocket();
      ws.on('error', (err) => console.error('WS error:', err.message));

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

      try {
        const ctx = ws.context({
          model_id: 'sonic-latest',
          voice: { mode: 'id', id: '6ccbfb76-1fc6-48f7-b71d-91ac6298247b' },
          output_format: { container: 'raw', encoding: 'pcm_f32le', sample_rate: 44100 },
          language: 'en',
        });

        console.log('Sending neutral text...');
        await ctx.push({ transcript: 'Well maybe if you just ' });

        console.log('Sending angry text...');
        await ctx.push({
          transcript: 'loosen up a little!',
          generation_config: { emotion: 'angry' },
        });

        await ctx.no_more_inputs();

        for await (const event of ctx.receive()) {
          if (event.type === 'chunk') {
            if (event.audio) file.write(event.audio);
          } else if (event.type === 'error') {
            throw new Error(`${event.title}: ${event.message}`);
          }
        }

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

    From [cartesia-js/examples/node\_examples.ts:265](https://github.com/cartesia-ai/cartesia-js/blob/v3.2.0/examples/node_examples.ts#L265)
  </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_websocket_emotion
    ```
  </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_websocket_emotion_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 ttsWebsocketEmotion
    ```
  </Tab>
</Tabs>
