Dev.to AI 🤖 Ai 👁 0 📖 5 min read

Build a Text-to-Speech App with ElevenLabs and Python

Introduction If you’ve ever wanted to turn a paragraph of text into a natural‑sounding voice, you’re in the right place. In this tutorial we’ll build a simple Python app that talks back to you using ElevenLabs – a stat

Introduction

If you’ve ever wanted to turn a paragraph of text into a natural‑sounding voice, you’re in the right place. In this tutorial we’ll build a simple Python app that talks back to you using ElevenLabs – a state‑of‑the‑art text‑to‑speech (TTS) platform that supports voice cloning, multi‑language synthesis, and low‑latency streaming. By the end you’ll have a reusable script that can:

  • Convert any string to an MP3 file
  • Choose from ElevenLabs’ library of premium voices
  • (Optional) Clone your own voice for a truly personalized experience

Let’s dive in!

Prerequisites

What you need Why
Python 3.8+ The language we’ll use for the demo
pip To install dependencies
An ElevenLabs account To get an API key (free tier available)
Basic familiarity with HTTP requests We’ll call the REST API directly

If you haven’t signed up yet, grab your API key from the ElevenLabs dashboard via this link: https://try.elevenlabs.io/kr07zfuqn1bp. The sign‑up is quick, and the free tier gives you 10 k characters per month—enough for testing.

Setting Up the Project

Create a new folder and set up a virtual environment:

mkdir elevenlabs-tts
cd elevenlabs-tts
python -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate

Install the required packages:

pip install requests tqdm

We’ll use requests for HTTP calls and tqdm to show a progress bar while the audio streams back.

Your First API Call

ElevenLabs exposes a straightforward /v1/text-to-speech/{voice_id} endpoint. Here’s a minimal Python function that sends text and writes the returned audio to disk:

import os
import requests
from tqdm import tqdm

ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")  # set this in your shell
BASE_URL = "https://api.elevenlabs.io/v1"

def synthesize(text: str, voice_id: str = "EXAVITQu4vr4xnSDxMaL", output_path: str = "output.mp3"):
    """
    Convert `text` to speech using ElevenLabs.
    Default voice_id points to the premium "Rachel" voice.
    """
    url = f"{BASE_URL}/text-to-speech/{voice_id}"
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "model_id": "eleven_monolingual_v1",   # default high‑quality model
        "voice_settings": {
            "stability": 0.75,
            "similarity_boost": 0.75
        }
    }

    # Stream the response so we can show a progress bar
    with requests.post(url, json=payload, headers=headers, stream=True) as r:
        r.raise_for_status()
        total = int(r.headers.get("content-length", 0))
        with open(output_path, "wb") as f, tqdm(
            desc="Downloading audio",
            total=total,
            unit="iB",
            unit_scale=True,
            unit_divisor=1024,
        ) as bar:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
                bar.update(len(chunk))

    print(f"✅ Audio saved to {output_path}")

Running the script

Save the function in a file called tts.py, add a small driver, and execute:

if __name__ == "__main__":
    import sys
    if not ELEVEN_API_KEY:
        sys.exit("❌ Set ELEVEN_API_KEY environment variable first")
    sample_text = "Hello, world! This is ElevenLabs speaking through Python."
    synthesize(sample_text)
export ELEVEN_API_KEY="your_api_key_here"   # macOS/Linux
# set ELEVEN_API_KEY=your_api_key_here     # Windows PowerShell
python tts.py

You should hear a crisp, human‑like voice in output.mp3. Feel free to swap the voice_id with any of the IDs listed in the ElevenLabs dashboard.

Using cURL (quick sanity check)

If you prefer a one‑liner, here’s a cURL command that does the same thing:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/EXAVITQu4vr4xnSDxMaL" \
  -H "xi-api-key: $ELEVEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text":"Testing ElevenLabs via curl!","model_id":"eleven_monolingual_v1"}' \
  --output test.mp3

Replace $ELEVEN_API_KEY with your actual key. The response will be an MP3 file named test.mp3.

Adding Voice Cloning

One of the coolest features of ElevenLabs is the ability to clone a custom voice. After uploading a few seconds of clean audio, the platform builds a model that mimics the speaker’s tone, cadence, and style.

Step‑by‑step

  1. Collect a sample – 30–60 seconds of clear speech (e.g., a short reading).
  2. Upload via the dashboard – Navigate to Voice Lab → Add Voice and follow the UI.
  3. Grab the new voice_id – Once the clone is ready, copy its ID.

Now you can call synthesize with that ID:

my_voice_id = "YOUR_CLONED_VOICE_ID"
synthesize("This is my own voice speaking through the API!", voice_id=my_voice_id)

The result feels like you recorded the audio yourself, but it’s generated instantly.

Putting It All Together – A Tiny CLI App

Let’s turn the snippet into a reusable command‑line tool:

# file: cli_tts.py
import argparse

def main():
    parser = argparse.ArgumentParser(description="ElevenLabs TTS CLI")
    parser.add_argument("text", help="Text to synthesize")
    parser.add_argument("-v", "--voice", default="EXAVITQu4vr4xnSDxMaL",
                        help="ElevenLabs voice ID (default: premium Rachel)")
    parser.add_argument("-o", "--output", default="speech.mp3",
                        help="Output file name")
    args = parser.parse_args()

    synthesize(args.text, voice_id=args.voice, output_path=args.output)

if __name__ == "__main__":
    main()

Run it like:

python cli_tts.py "Python developers love good APIs!" -v YOUR_CLONED_VOICE_ID -o my_voice.mp3

You now have a lightweight, pip‑installable tool you can embed in larger projects, bots, or automation pipelines.

Tips & Best Practices

Tip Reason
Cache generated files Re‑synthesizing the same sentence wastes quota. Store MP3s locally when possible.
Adjust stability & similarity_boost Lower stability yields more expressive speech; higher similarity keeps the voice close to the original clone.
Batch multiple sentences Concatenating a few short texts into one request reduces latency and API calls.
Respect rate limits ElevenLabs enforces a per‑minute request cap. Use exponential back‑off if you hit 429 Too Many Requests.

Wrapping Up

You now have a functional Python app that leverages ElevenLabs for high‑quality text‑to‑speech and voice cloning. The same concepts translate to other languages (JavaScript, Go, etc.) – the core is simply a POST request to the /v1/text-to-speech endpoint.

Feel free to experiment with:

  • Different languages by changing model_id to eleven_multilingual_v1
  • Streaming audio directly to a player instead of writing to disk
  • Integrating with Flask/FastAPI to serve TTS over HTTP

The possibilities are endless, and the API is designed to be developer‑friendly, so you can focus on building cool experiences rather than wrestling with audio processing.

Ready to give your apps a voice?

Grab your ElevenLabs API key and start building at https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding!

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.