Why Voice AI Matters for Game Characters
If you’ve ever played a game where the NPCs sound like they were recorded on a cheap phone, you know how much immersion can suffer. Modern players expect characters to speak with personality, emotion, and consistency—especially in narrative‑driven titles or RPGs where dialogue drives the story.
Text‑to‑speech (TTS) and voice cloning have come a long way. What used to be robotic, monotone output is now indistinguishable from a human voice actor in many cases. For indie developers or small studios, this opens a whole new world: you can give every side‑quest giver, shopkeeper, or enemy a unique voice without hiring a full cast.
In this article I’ll walk you through a practical workflow for generating voice samples for game characters, using the ElevenLabs API (the link you’ll see below is an affiliate link, but it works just like any other API key). By the end you’ll have a repeatable pipeline you can hook into Unity, Unreal, or any custom engine.
1. Sketch Out Your Dialogue Assets
Before you even touch code, decide what you need:
| Asset | Description | Typical Length |
|---|---|---|
| Character bios | Short text describing personality, accent, age. | 1‑2 sentences |
| Script lines | All spoken lines for a given character. | 5‑30 seconds each |
| Emotion tags | Optional markers like happy, angry, whisper. |
N/A |
Having a CSV or JSON file that maps character_id → voice_profile → lines will make the next steps painless. Example JSON:
{
"npc_merchant": {
"voice_id": "elevenlabs-voice-123",
"lines": [
{"text": "Welcome, traveler! Care to browse my wares?", "emotion": "cheerful"},
{"text": "I’m sorry, that’s beyond your budget.", "emotion": "sympathetic"}
]
}
}
2. Choose a Voice Model
ElevenLabs provides a library of pre‑trained voices and also lets you clone a custom voice from a few minutes of audio. For most indie projects, picking a pre‑made voice is enough, but cloning is handy when you want a signature voice for a main protagonist.
Tip: Use the same voice for a single character across all scenes. Consistency prevents players from feeling a “voice break” that can break immersion.
Quick test with the web UI
- Sign up at the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp
- Pick a voice you like and type a short line.
- Download the resulting MP3 and listen.
If it feels right, copy the voice_id (it looks like voice-abcdef123456). You’ll need it for the API calls.
3. Set Up the ElevenLabs API
You’ll need an API key from your ElevenLabs dashboard. Store it securely—never commit it to source control. I like using an environment variable:
export ELEVENLABS_API_KEY="your-secret-key"
Python wrapper (requests)
import os
import requests
API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"
def synthesize(text: str, voice_id: str, stability: float = 0.75, similarity_boost: float = 0.85):
url = f"{BASE_URL}/text-to-speech/{voice_id}"
headers = {
"xi-api-key": API_KEY,
"Content-Type": "application/json"
}
payload = {
"text": text,
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": stability,
"similarity_boost": similarity_boost
}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.content # binary audio (mp3)
# Example usage
audio_bytes = synthesize(
text="Welcome, traveler! Care to browse my wares?",
voice_id="voice-abcdef123456"
)
# Save to disk for Unity/Unreal import
with open("merchant_greeting.mp3", "wb") as f:
f.write(audio_bytes)
Curl alternative (useful for quick testing)
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/voice-abcdef123456" \
-H "xi-api-key: $ELEVENLABS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "I’m sorry, that’s beyond your budget.",
"model_id": "eleven_monolingual_v1",
"voice_settings": {"stability":0.75,"similarity_boost":0.85}
}' --output merchant_decline.mp3
Both snippets produce an MP3 file that you can drop directly into your game’s asset pipeline.
4. Batch‑Generate an Entire Character’s Lines
When you have dozens of lines, automate the loop. Here’s a compact script that reads the JSON from step 1 and spits out a folder of audio files.
import json
from pathlib import Path
DATA_PATH = Path("dialogue.json")
OUTPUT_ROOT = Path("Assets/Audio/Characters")
OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)
with open(DATA_PATH) as f:
data = json.load(f)
for char_id, char_info in data.items():
voice_id = char_info["voice_id"]
char_folder = OUTPUT_ROOT / char_id
char_folder.mkdir(exist_ok=True)
for i, line in enumerate(char_info["lines"]):
filename = char_folder / f"line_{i:03}.mp3"
if filename.exists():
continue # skip already generated files
audio = synthesize(
text=line["text"],
voice_id=voice_id,
stability=0.7,
similarity_boost=0.9
)
with open(filename, "wb") as out:
out.write(audio)
print(f"✅ {filename}")
Run it once, and you’ll have a tidy folder structure:
Assets/
└─ Audio/
└─ Characters/
├─ npc_merchant/
│ ├─ line_000.mp3
│ └─ line_001.mp3
└─ npc_guard/
└─ ...
You can now import these folders into Unity (drag‑and‑drop) or Unreal (import as Sound Wave assets) and reference them by name in your dialogue system.
5. Adding Emotion & Prosody
ElevenLabs lets you tweak stability (how steady the voice is) and similarity_boost (how close it stays to the base voice). Play with those values per emotion tag:
| Emotion | Stability | Similarity Boost |
|---|---|---|
| Calm | 0.85 | 0.80 |
| Angry | 0.60 | 0.95 |
| Whisper | 0.90 | 0.70 |
You can even prepend a short cue to the text, like "[whisper] I need your help." and adjust the parameters in code based on the tag.
6. Post‑Processing (Optional)
Raw MP3s from ElevenLabs sound great, but you might want:
-
Normalization – ensure all lines have the same loudness. Use
ffmpeg:
ffmpeg -i input.mp3 -af "loudnorm=I=-16:TP=-1.5:LRA=11" output_normalized.mp3
- Compression – reduce file size for mobile builds:
ffmpeg -i output_normalized.mp3 -b:a 64k merchant_greeting_compressed.mp3
- 3‑D Audio – Unity’s AudioSource spatial blend or Unreal’s attenuation settings can give the illusion that the voice is coming from a specific location.
7. Hooking Into Your Dialogue System
Most engines already have a way to play a sound by name. Here’s a tiny Unity C# snippet that loads a clip from the Resources folder and plays it:
using UnityEngine;
public class VoicePlayer : MonoBehaviour
{
public void PlayLine(string characterId, int lineIndex)
{
string path = $"Characters/{characterId}/line_{lineIndex:D3}";
AudioClip clip = Resources.Load<AudioClip>(path);
GetComponent<AudioSource>().clip = clip;
GetComponent<AudioSource>().Play();
}
}
Just make sure your generated MP3s are imported as AudioClip assets (Unity will handle the conversion). In Unreal, you’d use a SoundWave reference and call PlaySoundAtLocation.
8. Managing Costs
ElevenLabs charges per generated character second. For a typical RPG with ~5 000 seconds of dialogue, you’re looking at a few hundred dollars—still cheaper than a full voice cast. Keep an eye on the usage dashboard and consider generating only the lines you need for the current build; you can always add more later.
9. Common Pitfalls & How to Avoid Them
| Issue | Why it Happens | Fix |
|---|---|---|
| Audio clipping | Volume too high after normalization | Use ffmpeg loudnorm with a target integrated loudness of –16 LUFS. |
| Mismatched accents | Using the same voice for characters of different nationalities | Choose distinct base voices or clone a voice with the appropriate accent. |
| Long latency | Generating on‑the‑fly during gameplay | Pre‑generate all lines offline; only the playback happens in‑game. |
| License confusion | Forgetting to attribute commercial use | ElevenLabs’ API key includes commercial rights; just keep your key secure. |
10. Next Steps
- Create a voice bank for each major NPC type.
- Automate the batch script as part of your CI pipeline so new lines are generated whenever the dialogue JSON changes.
- Experiment with emotion parameters to give your characters subtle personality shifts.
With a solid pipeline, you’ll spend more time polishing gameplay and less time coordinating recording sessions.
Ready to give your game characters a real voice?
Give ElevenLabs a spin using the affiliate link below, grab an API key, and start generating high‑quality voice samples today:
https://try.elevenlabs.io/kr07zfuqn1bp
Happy coding, and may your NPCs always sound as epic as the worlds you build!
Top comments (0)