- Python
- Python (Async)
- TypeScript
def tts_websocket_emotion(client: Cartesia) -> None:
"""Demonstrates changing emotion mid-stream using generation_config."""
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
)
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)
print(f"Saved audio to {filename}")
print(f"Play with: ffplay -f f32le -ar 44100 {filename}")
async def tts_websocket_emotion_async(client: AsyncCartesia) -> None:
"""Demonstrates changing emotion mid-stream using generation_config."""
output_format = {"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100}
async 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
)
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)
print(f"Saved audio to {filename}")
print(f"Play with: ffplay -f f32le -ar 44100 {filename}")
async function ttsWebsocketEmotion(client: Cartesia): Promise<void> {
/** Demonstrates changing emotion mid-stream using generation_config. */
const ws = await client.tts.websocket();
ws.on('error', (err) => console.error('WS error:', err.message));
const ctx = ws.context({
model_id: 'sonic-3',
voice: { mode: 'id', id: '6ccbfb76-1fc6-48f7-b71d-91ac6298247b' },
output_format: { container: 'raw', encoding: 'pcm_f32le', sample_rate: 44100 },
});
console.log('Sending neutral text...');
await ctx.push({ transcript: 'Well maybe if you just ' });
console.log('Sending angry text...');
await ctx.send({
model_id: 'sonic-3',
voice: { mode: 'id', id: '6ccbfb76-1fc6-48f7-b71d-91ac6298247b' },
output_format: { container: 'raw', encoding: 'pcm_f32le', sample_rate: 44100 },
transcript: 'loosen up a little!',
continue: true,
generation_config: { emotion: 'angry' },
});
await ctx.no_more_inputs();
const filename = `tts_emotion_${timestamp()}.pcm`;
const file = fs.createWriteStream(filename);
for await (const event of ctx.receive()) {
if (event.type === 'chunk') {
if (event.audio) file.write(event.audio);
}
}
file.end();
ws.close();
console.log(`Saved audio to ${filename}`);
console.log(`Play with: ffplay -f f32le -ar 44100 ${filename}`);
}
Run this example
- Python
- Python (Async)
- TypeScript
cd cartesia-python
CARTESIA_API_KEY=YOUR_KEY python3 examples/examples.py tts_websocket_emotion
cd cartesia-python
CARTESIA_API_KEY=YOUR_KEY python3 examples/async_examples.py tts_websocket_emotion_async
cd cartesia-js
CARTESIA_API_KEY=YOUR_KEY npx ts-node examples/node_examples.ts ttsWebsocketEmotion