Build a Text-to-Speech App with ElevenLabs and Python
Why Text‑to‑Speech Matters Today If you’ve ever built a chatbot, an accessibility feature, or a voice‑driven game, you know that natural‑sounding speech can turn a good product into a great one. Modern TTS engines have
Why Text‑to‑Speech Matters Today
If you’ve ever built a chatbot, an accessibility feature, or a voice‑driven game, you know that natural‑sounding speech can turn a good product into a great one. Modern TTS engines have moved far beyond robotic monotones; they can now mimic the nuances of human prosody, emotion, and even a specific speaker’s timbre.
That’s where ElevenLabs shines. Their API delivers high‑quality, low‑latency audio that’s perfect for anything from podcasts to interactive assistants. In this post we’ll walk through a complete, production‑ready Python app that:
- Sends plain text to ElevenLabs and receives an MP3 file.
- (Optional) Clones a custom voice from a short recording.
- Saves the audio locally and plays it back on the fly.
By the end you’ll have a reusable module you can drop into any Python project.
Prerequisites
| What you need | Why |
|---|---|
| Python 3.8+ | Modern syntax and type hints |
| An ElevenLabs account | API key for authentication (sign up via the affiliate link below) |
ffmpeg installed (optional) |
Enables on‑the‑fly playback with pydub
|
Basic familiarity with requests
|
We’ll be making HTTP calls |
If you don’t have an ElevenLabs account yet, grab one here: https://try.elevenlabs.io/kr07zfuqn1bp. The sign‑up is free and gives you a generous quota to experiment with.
Installing the Dependencies
Open a terminal and run:
# Create a virtual environment (highly recommended)
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install the required packages
pip install requests pydub tqdm
If you plan to play audio directly from Python, install ffmpeg:
-
macOS:
brew install ffmpeg -
Ubuntu:
sudo apt-get install ffmpeg -
Windows: Download the static build from https://ffmpeg.org and add it to your
PATH.
Getting Your ElevenLabs API Key
- Log in to the ElevenLabs dashboard.
- Navigate to API Keys → Create new key.
- Copy the generated key; you’ll need it in the code.
Never commit this key to source control. Store it in an environment variable:
export ELEVENLABS_API_KEY="your-secret-key"
In Windows PowerShell:
$env:ELEVENLABS_API_KEY = "your-secret-key"
A Minimal TTS Wrapper
Let’s encapsulate the HTTP logic in a small class. Save this as elevenlabs_tts.py.
import os
import json
import requests
from pathlib import Path
from typing import Optional
class ElevenLabsTTS:
BASE_URL = "https://api.elevenlabs.io/v1"
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv("ELEVENLABS_API_KEY")
if not self.api_key:
raise ValueError("ElevenLabs API key not found. Set ELEVENLABS_API_KEY env var.")
self.headers = {
"xi-api-key": self.api_key,
"Content-Type": "application/json",
}
def generate(
self,
text: str,
voice_id: str = "EXAVITQu4vr4xnSDxMaL", # default "Rachel"
model_id: str = "eleven_monolingual_v1",
stability: float = 0.75,
similarity_boost: float = 0.75,
) -> bytes:
"""
Sends text to ElevenLabs and returns raw MP3 bytes.
"""
payload = {
"text": text,
"model_id": model_id,
"voice_settings": {
"stability": stability,
"similarity_boost": similarity_boost,
},
}
url = f"{self.BASE_URL}/text-to-speech/{voice_id}"
response = requests.post(url, headers=self.headers, json=payload, timeout=30)
response.raise_for_status()
return response.content
def save_to_file(self, audio_bytes: bytes, filename: Path) -> Path:
"""Write MP3 bytes to disk, creating parent dirs if needed."""
filename.parent.mkdir(parents=True, exist_ok=True)
filename.write_bytes(audio_bytes)
return filename
How it works
-
voice_id: Each voice in ElevenLabs has a UUID. The default points to the public “Rachel” voice, but you can replace it with any custom voice you’ve created (see the next section). -
stability&similarity_boost: Tweaking these values changes how consistent the voice sounds and how closely it matches a reference voice. -
Error handling:
response.raise_for_status()will throw an exception for any non‑2xx response, giving you a clear traceback.
Quick Demo: Convert a Paragraph to Speech
Create a file named demo.py:
import sys
from pathlib import Path
from elevenlabs_tts import ElevenLabsTTS
from pydub import AudioSegment
from pydub.playback import play
def main(text: str, out_path: Path):
tts = ElevenLabsTTS()
print("⏳ Generating audio...")
audio_bytes = tts.generate(text)
tts.save_to_file(audio_bytes, out_path)
print(f"✅ Audio saved to {out_path}")
# Optional: play back immediately
audio = AudioSegment.from_file(out_path, format="mp3")
play(audio)
if __name__ == "__main__":
sample_text = """\
Welcome to the future of voice AI! With ElevenLabs, you can turn any text into a natural‑sounding voice in seconds. \
This demo shows how easy it is to integrate TTS into your Python projects."""
output_file = Path("output") / "welcome.mp3"
main(sample_text, output_file)
Run it:
python demo.py
You should hear a clear, expressive voice reading the paragraph, and an output/welcome.mp3 file will appear on disk.
Adding Voice Cloning (Optional but Powerful)
ElevenLabs lets you create a personal voice from just a few minutes of audio. Here’s a high‑level flow:
- Upload a sample (WAV/MP3) via the API.
-
Create a voice – the service returns a new
voice_id. -
Use the new voice_id in the
generatemethod above.
Below is a concise script that automates steps 1‑2. Save as clone_voice.py.
import os
import requests
from pathlib import Path
API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"
def upload_sample(sample_path: Path) -> str:
"""Upload a 15‑second sample and return the temporary upload_id."""
url = f"{BASE_URL}/samples"
headers = {"xi-api-key": API_KEY}
files = {"sample": open(sample_path, "rb")}
resp = requests.post(url, headers=headers, files=files)
resp.raise_for_status()
return resp.json()["sample_id"]
def create_voice(sample_id: str, voice_name: str) -> str:
"""Create a new voice from a sample."""
url = f"{BASE_URL}/voices/add"
payload = {
"name": voice_name,
"samples": [sample_id],
"description": f"Custom voice generated from {voice_name}",
}
headers = {"xi-api-key": API_KEY, "Content-Type": "application/json"}
resp = requests.post(url, headers=headers, json=payload)
resp.raise_for_status()
return resp.json()["voice_id"]
if __name__ == "__main__":
# Replace with your own short recording (max 30 seconds)
sample_file = Path("my_voice_sample.wav")
sample_id = upload_sample(sample_file)
voice_id = create_voice(sample_id, "MyCustomVoice")
print(f"✅ New voice created! ID: {voice_id}")
Tip: Keep the sample clean—no background noise, consistent speaking pace, and a sample length of 10‑30 seconds yields the best results.
Now you can call tts.generate(..., voice_id=voice_id) and hear your voice reading any text.
Handling Rate Limits and Errors Gracefully
Production services need robust error handling. Here’s a quick wrapper you can drop into ElevenLabsTTS:
import time
from requests.exceptions import HTTPError, Timeout
def _request_with_retry(self, method, url, **kwargs):
max_retries = 3
backoff = 2 # seconds
for attempt in range(max_retries):
try:
resp = requests.request(method, url, headers=self.headers, timeout=30, **kwargs)
resp.raise_for_status()
return resp
except HTTPError as e:
if resp.status_code == 429: # Too Many Requests
wait = int(resp.headers.get("Retry-After", backoff))
print(f"⏳ Rate limited, sleeping {wait}s...")
time.sleep(wait)
else:
raise
except (Timeout, ConnectionError) as e:
print(f"⚠️ Network issue, retry {attempt + 1}/{max_retries}")
time.sleep(backoff)
raise RuntimeError("Failed after several retries")
Replace the direct requests.post call in generate with:
resp = self._request_with_retry("POST", f"{self.BASE_URL}/text-to-speech/{voice_id}", json=payload)
return resp.content
Now your app will back off automatically if ElevenLabs throttles you.
Next Steps: Integrate with Your Favorite Frameworks
-
FastAPI / Flask – expose a
/speakendpoint that returns the MP3 stream directly to browsers. - Discord bots – feed the MP3 into voice channels for real‑time narration.
- IoT devices – stream the bytes over MQTT to a Raspberry Pi speaker.
Because the core logic lives in a single class, swapping the transport layer is trivial.
Wrap‑Up & Call to Action
You’ve just built a fully functional TTS pipeline, explored voice cloning, and added basic resiliency—all powered by ElevenLabs’ state‑of‑the‑art speech synthesis. The API is straightforward, the Python SDK is lightweight, and the quality of the output rivals commercial products.
Ready to give your app a voice that truly stands out? Grab your free ElevenLabs API key now and start experimenting: https://try.elevenlabs.io/kr07zfuqn1bp.
Happy coding, and may your projects speak louder than words!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.