Why a Multi‑Voice Dialogue Generator?
Imagine a chatbot that can switch between characters—think a game NPC, a virtual assistant that mimics different accents, or a storytelling app where each narrator has a distinct voice. With modern text‑to‑speech (TTS) APIs, this is no longer a futuristic concept; it’s something you can prototype in a few hours.
In this guide we’ll walk through building a multi‑voice dialogue generator using Python and the ElevenLabs API (the service that powers some of the most natural‑sounding voice clones on the market). By the end you’ll have a small but flexible server that can:
- Accept a line of text and a voice identifier
- Synthesize speech on‑the‑fly
- Return an audio file (or a streaming URL) that you can play in a web UI or embed in a game
Let’s dive in!
Prerequisites
| What you need | Why it matters |
|---|---|
| Python 3.9+ | Modern syntax, async support |
requests or httpx
|
Simple HTTP client for the API |
| An ElevenLabs account (free tier works) | Provides the TTS endpoint and voice models |
| A microphone/headphones (optional) | To test the generated audio locally |
If you don’t have an ElevenLabs account yet, sign up via the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp – you’ll get a starter credit that’s perfect for experimentation.
Getting Your API Key
- Log in to the ElevenLabs dashboard.
- Navigate to API → Tokens.
- Click Create new token and give it a name like “multi‑voice‑demo”.
- Copy the token – you’ll need it in your code (keep it secret!).
Store the token in an environment variable for safety:
export ELEVENLABS_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxx"
Understanding ElevenLabs Voices
ElevenLabs ships with a handful of pre‑trained voices (e.g., “Rachel”, “Domi”) and lets you upload custom voice clones. Each voice has a unique ID you’ll reference when you call the /v1/text-to-speech/{voice_id} endpoint.
You can list all available voices with a simple curl command:
curl -H "xi-api-key: $ELEVENLABS_API_KEY" \
https://api.elevenlabs.io/v1/voices
The response contains an array of objects; note the voice_id fields. Those IDs are what we’ll pass to the generator.
Setting Up a Minimal Flask Server
Below is a complete, runnable example that exposes a /speak endpoint. It accepts JSON payloads with text and voice_id, calls ElevenLabs, and returns the audio as a base‑64 string (easy to embed in a web page).
# app.py
import os
import base64
import httpx
from flask import Flask, request, jsonify
app = Flask(__name__)
API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"
HEADERS = {
"xi-api-key": API_KEY,
"Content-Type": "application/json"
}
def synthesize(text: str, voice_id: str) -> bytes:
"""Call ElevenLabs TTS and return raw MP3 bytes."""
url = f"{BASE_URL}/text-to-speech/{voice_id}"
payload = {
"text": text,
"model_id": "eleven_monolingual_v1", # default high‑quality model
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85
}
}
response = httpx.post(url, headers=HEADERS, json=payload, timeout=30)
response.raise_for_status()
return response.content # MP3 binary
@app.route("/speak", methods=["POST"])
def speak():
data = request.get_json()
text = data.get("text", "")
voice_id = data.get("voice_id")
if not text or not voice_id:
return jsonify({"error": "Both 'text' and 'voice_id' are required"}), 400
try:
audio_bytes = synthesize(text, voice_id)
b64_audio = base64.b64encode(audio_bytes).decode("utf-8")
return jsonify({"audio_base64": b64_audio})
except httpx.HTTPStatusError as exc:
return jsonify({"error": str(exc)}), exc.response.status_code
if __name__ == "__main__":
app.run(debug=True)
How it works
- Receive a request – The client sends JSON with the line to be spoken and the target voice ID.
-
Call ElevenLabs –
synthesize()posts to the TTS endpoint, passing the text and a few optional voice settings (stability and similarity boost control how “steady” the voice sounds). - Return audio – The MP3 bytes are base‑64 encoded so the response can be consumed by browsers without dealing with multipart file uploads.
Adding Multiple Voices to a Conversation
Now that we can generate a single utterance, let’s orchestrate a back‑and‑forth dialogue. The trick is to keep a conversation state (e.g., an array of {speaker, text} objects) and iterate through it, swapping the voice_id each turn.
# conversation_demo.py
import os
import httpx
API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"
HEADERS = {"xi-api-key": API_KEY, "Content-Type": "application/json"}
# Example voice IDs – replace with the IDs you fetched earlier
VOICES = {
"alice": "01a2b3c4-5678-90ab-cdef-1234567890ab", # a warm female voice
"bob": "09f8e7d6-5432-10fe-dcba-0987654321fe" # a deep male voice
}
def speak_line(text, voice_id):
url = f"{BASE_URL}/text-to-speech/{voice_id}"
payload = {
"text": text,
"model_id": "eleven_monolingual_v1"
}
resp = httpx.post(url, headers=HEADERS, json=payload)
resp.raise_for_status()
return resp.content # MP3
def run_dialogue():
dialogue = [
{"speaker": "alice", "text": "Hey Bob, did you finish the report?"},
{"speaker": "bob", "text": "Almost! Just need a coffee first."},
{"speaker": "alice", "text": "No problem, I’ll grab one for you."}
]
for turn in dialogue:
voice_id = VOICES[turn["speaker"]]
audio = speak_line(turn["text"], voice_id)
# Save each line to a file for later playback
filename = f"{turn['speaker']}_{dialogue.index(turn)}.mp3"
with open(filename, "wb") as f:
f.write(audio)
print(f"Saved {filename}")
if __name__ == "__main__":
run_dialogue()
Why this matters
- Character differentiation – By assigning each persona its own voice ID, listeners instantly recognize who’s speaking.
- Scalability – You can store voice IDs in a database, letting non‑technical users add new characters via a simple admin UI.
- Extensibility – The same pattern works for more than two speakers, for multilingual bots, or for dynamic voice‑cloning (ElevenLabs also lets you upload a few seconds of audio to create a custom voice).
Tips for Real‑World Use
| Tip | Explanation |
|---|---|
| Cache audio | Re‑synthesizing the same line repeatedly wastes credits. Store the MP3 (or its hash) after the first generation. |
Adjust stability |
Lower values make the voice sound more expressive (good for excitement), higher values keep it steady (ideal for narration). |
| Chunk long texts | ElevenLabs limits the input length (≈ 5 KB). Split paragraphs into sentences and concatenate the resulting MP3s. |
| Rate‑limit requests | Free tiers have a per‑minute cap. Use exponential back‑off if you hit 429 Too Many Requests. |
| Use WebSockets for live chat | If you need real‑time playback (e.g., in a game), push the base‑64 audio over a socket instead of HTTP polling. |
Deploying to the Cloud
For a production‑ready service you can:
- Containerize the Flask app with Docker:
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
ENV PORT=8080
CMD ["gunicorn", "-b", "0.0.0.0:$PORT", "app:app"]
- Push to a managed platform (Render, Fly.io, or AWS Elastic Beanstalk).
- Set the
ELEVENLABS_API_KEYas a secret in your hosting provider.
With a proper CI/CD pipeline you’ll have a scalable multi‑voice TTS microservice ready for any app—from Discord bots to interactive e‑learning platforms.
Wrap‑Up
You now have a functional pipeline:
- Fetch voice IDs from ElevenLabs.
- Expose an endpoint that receives text and a voice selector.
- Synthesize the speech using the API (with optional stability tweaks).
- Return or store the audio for playback.
The core of the system is only a few lines of code, yet the possibilities are huge: voice‑driven RPG dialogues, multilingual customer support agents, or even AI‑generated audiobooks with distinct narrator voices.
Ready to give it a spin?
If you’re curious about how natural a cloned voice can sound, sign up through this link and start experimenting with the API right away: https://try.elevenlabs.io/kr07zfuqn1bp. You’ll get instant credits, a clean dashboard, and the same powerful voice models we used in this tutorial.
Happy coding, and may your characters always sound as vivid as their stories!
Top comments (0)