import asyncio
import websockets
import json
import base64
async def multi_speaker_demo():
async with websockets.connect(
"wss://api.kugelaudio.com/ws/tts/multi?api_key=YOUR_API_KEY"
) as ws:
# Initialize narrator context
await ws.send(json.dumps({
"text": " ",
"context_id": "narrator",
"voice_settings": {"voice_id": 1071},
}))
# Create character context
await ws.send(json.dumps({
"text": " ",
"context_id": "character",
"voice_settings": {"voice_id": 1072},
}))
# Send text to different speakers
await ws.send(json.dumps({
"text": "The story begins.",
"context_id": "narrator",
"flush": True,
}))
await ws.send(json.dumps({
"text": "Hello, I'm the main character!",
"context_id": "character",
"flush": True,
}))
# Receive audio from both contexts
async for message in ws:
data = json.loads(message)
if "audio" in data:
context_id = data["context_id"]
audio_bytes = base64.b64decode(data["audio"])
play_audio(context_id, audio_bytes)
if data.get("context_closed"):
# Per-context usage for this conversation: audio time + charge
print(f"[{data['context_id']}] usage: {data.get('usage')}")
if data.get("session_closed"):
break
# Close when done
await ws.send(json.dumps({"close_socket": True}))
asyncio.run(multi_speaker_demo())