DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Multi-Voice Dialogue Generator

Why a Multi‑Voice Dialogue Generator Matters

When building conversational agents, we often stop at a single, generic voice. In the real world, interactions happen between multiple people, each with a distinct timbre, accent, and speaking style. Imagine a virtual customer support team, a multi‑character storytelling app, or an AI‑driven game where each NPC has a unique voice. A multi‑voice dialogue generator lets you bring that realism to life without recording thousands of samples for every character.

Below, I’ll walk through the core components you need, show how to wire everything together with a quick Python prototype, and point you to a powerful TTS platform that makes voice cloning painless.


1. The Building Blocks

Component Role Why it matters
Text Generation Generates the raw dialogue lines Determines what the characters say
Speaker Embedding Encodes a voice’s unique characteristics Allows a single model to “switch” voices
Text‑to‑Speech (TTS) Synthesizes speech from text & speaker embedding Turns text into audible audio
Dialogue Management Keeps track of turns, context, and character identity Ensures natural back‑and‑forth flow

Most developers will rely on third‑party services for the heavy lifting: a language model for text and a TTS engine that supports voice cloning. The rest is glue code and a bit of audio post‑processing.


2. Picking a Voice Cloning Service

There are a handful of TTS providers that support voice cloning via a simple API. I’ve experimented with several, and ElevenLabs consistently delivers high‑fidelity, natural‑sounding voices with an intuitive API. They also provide an easy way to upload a few minutes of audio and generate a speaker embedding that can be reused across your app.

Tip: Use the affiliate link https://try.elevenlabs.io/kr07zfuqn1bp to sign up—you’ll get a free tier with generous limits.


3. Setting Up Your Environment

# Create a virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install openai requests pydub
Enter fullscreen mode Exit fullscreen mode
  • openai – for text generation (ChatGPT or GPT‑4)
  • requests – HTTP client for ElevenLabs
  • pydub – simple audio manipulation (concatenation, trimming, etc.)

Make sure you have an OpenAI API key and an ElevenLabs API key. Store them as environment variables:

export OPENAI_API_KEY="sk-..."
export ELEVENLABS_API_KEY="eyJhbGciOi..."
Enter fullscreen mode Exit fullscreen mode

4. Step‑by‑Step: From Prompt to Audio

4.1. Generate Dialogue Lines

We’ll use OpenAI’s chat completion to generate a short script between two characters, “Alice” and “Bob”.

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

def generate_script():
    prompt = (
        "Write a short conversation between Alice and Bob about planning a weekend trip. "
        "Each line should start with the speaker name, e.g., \"Alice: ...\". "
        "Keep it under 10 lines."
    )
    response = openai.ChatCompletion.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7,
    )
    return response.choices[0].message.content.strip()

script = generate_script()
print(script)
Enter fullscreen mode Exit fullscreen mode

Sample output:

Alice: Hey Bob, are you free this Saturday for a hiking trip?
Bob: Absolutely! I’ve been waiting for the weather to clear up.
Alice: Great, I found a trail that’s only a 30‑minute drive away.
Bob...
Enter fullscreen mode Exit fullscreen mode

4.2. Split the Script into Turns

from typing import List, Tuple

def parse_turns(script: str) -> List[Tuple[str, str]]:
    turns = []
    for line in script.splitlines():
        if ":" in line:
            speaker, text = line.split(":", 1)
            turns.append((speaker.strip(), text.strip()))
    return turns

turns = parse_turns(script)
print(turns)
Enter fullscreen mode Exit fullscreen mode

Output:

[('Alice', 'Hey Bob, are you free this Saturday for a hiking trip?'),
 ('Bob', 'Absolutely! I’ve been waiting for the weather to clear up.'),
 ...]
Enter fullscreen mode Exit fullscreen mode

4.3. Get Speaker Embeddings from ElevenLabs

First, upload a short audio clip for each character to create a speaker model.

# Example: upload 30‑second clip for Alice
curl -X POST "https://api.elevenlabs.io/v1/speakers" \
     -H "xi-api-key: $ELEVENLABS_API_KEY" \
     -H "Content-Type: multipart/form-data" \
     -F "name=Alice" \
     -F "audio=@alice_demo.wav" \
     -F "description=Alice's voice"
Enter fullscreen mode Exit fullscreen mode

Repeat for Bob. The API will return a speaker_id you’ll use later.

4.4. Synthesize Each Turn

import json
import requests
from pydub import AudioSegment

ELEVEN_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"

def synthesize_turn(speaker_id: str, text: str, voice_params: dict) -> AudioSegment:
    payload = {
        "text": text,
        "voice_settings": voice_params,
    }
    headers = {
        "xi-api-key": os.getenv("ELEVENLABS_API_KEY"),
        "Content-Type": "application/json",
    }
    response = requests.post(
        f"{ELEVEN_API_URL}/{speaker_id}",
        headers=headers,
        data=json.dumps(payload),
        stream=True,
    )
    response.raise_for_status()
    # ElevenLabs returns raw audio bytes
    audio = AudioSegment.from_file(response.raw, format="mp3")
    return audio

# Example voice settings (you can tweak pitch, speed, etc.)
voice_settings = {
    "stability": 0.75,
    "similarity_boost": 0.85,
    "style": 0,
    "use_speaker_boost": True,
}

# Assuming you have speaker IDs
speaker_ids = {"Alice": "alice_speaker_id", "Bob": "bob_speaker_id"}

audio_segments = []
for speaker, line in turns:
    seg = synthesize_turn(speaker_ids[speaker], line, voice_settings)
    audio_segments.append(seg)

# Concatenate all turns
final_audio = sum(audio_segments)
final_audio.export("conversation.mp3", format="mp3")
print("Saved conversation.mp3")
Enter fullscreen mode Exit fullscreen mode

Now you have a single MP3 that alternates between Alice and Bob, each speaking with a distinct, natural voice.


5. Enhancing the Experience

5.1. Adding Pauses & Intonation

Use pydub to insert small silences between turns so listeners can catch up.

silence = AudioSegment.silent(duration=500)  # 0.5 second
audio_with_pauses = AudioSegment.empty()
for seg in audio_segments:
    audio_with_pauses += seg + silence
audio_with_pauses.export("conversation_with_pauses.mp3", format="mp3")
Enter fullscreen mode Exit fullscreen mode

5.2. Real‑Time Streaming

ElevenLabs supports streaming audio. For a live chatbot, you can stream each generated line directly to a speaker or browser audio element, reducing latency.

# Pseudo‑code: stream audio chunks as they arrive
for chunk in elevenlabs_stream_response:
    audio_chunk = AudioSegment.from_raw(chunk, format="mp3")
    play(audio_chunk)  # e.g., using simpleaudio or pyaudio
Enter fullscreen mode Exit fullscreen mode

5.3. Custom Voice Attributes

ElevenLabs allows you to tweak style, pitch, and speed per request. Experiment with different values to match a character’s personality—e.g., a higher pitch for a youthful narrator or a slower pace for a contemplative elder.


6. Common Pitfalls & Quick Fixes

Symptom Likely Cause Fix
Audio glitches or abrupt cuts Using short speaker clips that lack enough phoneme coverage Record at least 1–2 minutes of varied speech
Over‑familiar voice Using the same speaker ID for multiple characters Create separate speaker IDs per character
High latency Making separate API calls per turn Batch multiple lines into a single request if supported
Licensing issues Using copyrighted audio for cloning Only use royalty‑free or your own recordings

7. Going Beyond Text‑to‑Speech

  • Emotion Injection: Combine ElevenLabs’ voice settings with a sentiment analysis model to add emotional tone to each line.
  • Dynamic Character Switching: In a game, you can swap speaker IDs on the fly based on player choices.
  • Multilingual Support: ElevenLabs currently supports multiple languages—just switch the lang parameter in the payload.

8. Wrap‑Up

Creating a realistic, multi‑voice dialogue generator is surprisingly straightforward once you have the right tools:

  1. Generate dialogue with a language model.
  2. Parse the script into speaker turns.
  3. Clone each character’s voice with ElevenLabs.
  4. Synthesize and stitch the audio together.

With the code snippets above, you can prototype a small demo in under an hour. Scale it up by adding more characters, integrating with a chat UI, or embedding the audio in a mobile app.


Call to Action

Ready to bring your characters to life? Sign up for ElevenLabs today via the affiliate link below, and start cloning voices with just a few minutes of audio. The free tier gives you plenty of credits to experiment, and the quality will blow your users away.

Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp

Top comments (0)