ai newsMi., 21. Okt.
EilmeldungMeta to create a new class of shares to fund AI push

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‑enabled game, you know that a natural‑sounding voice can turn a static experience into something engaging and human‑like. Modern TTS engines are no longer limited to robotic monotones – they can ca

dev.toMittwoch 21:59 · 21.10.5 Min. Lesezeit
Bild: dev.to

Wer schon einmal einen Chatbot, eine Barrierefreiheitsfunktion oder ein sprachgesteuertes Spiel gebaut hat, weiß, dass eine natürlich klingende Stimme ein statisches Erlebnis in etwas Lebendiges und Menschliches verwandeln kann. Moderne TTS-Engines beschränken sich längst nicht mehr auf roboterhafte Monotonie – sie können Emotionen und Intonation erfassen und sogar den Stil eines bestimmten Sprechers imitieren.

Genau dort spielt ElevenLabs seine Stärken aus. Die API liefert hochwertige neuronale Stimmen, die sich leicht integrieren lassen, und das Preismodell eignet sich sowohl für Hobbyprojekte als auch für Produktionsanwendungen. In diesem Beitrag bauen wir Schritt für Schritt eine einfache Python-Anwendung, die Text an ElevenLabs sendet, eine Audiodatei empfängt und diese abspielt. Am Ende haben Sie ein wiederverwendbares Skript, das Sie in jedes Projekt einbauen können.

Halten Sie dieses Token geheim – behandeln Sie es wie ein Passwort.

pip install httpx python-dotenv pydub httpx ist ein moderner asynchroner HTTP-Client. python-dotenv lädt Umgebungsvariablen aus einer.env-Datei. pydub eignet sich bequem zum Abspielen oder Konvertieren der zurückgegebenen MP3-Datei. (Außerdem muss ffmpeg auf Ihrem System installiert sein; unter macOS können Sie brew install ffmpeg verwenden, unter Ubuntu sudo apt-get install ffmpeg.) Erstellen Sie eine.env-Datei im Stammverzeichnis Ihres Projekts:

ELEVENLABS_API_KEY=your_api_key_here 3️⃣ Die zentrale TTS-Funktion Im Folgenden sehen Sie eine minimale asynchrone Funktion, die mit ElevenLabs kommuniziert. Sie nimmt den auszusprechenden Text sowie die Voice-ID entgegen (wir verwenden vorerst die Standardstimme „Rachel“) und gibt den Pfad zu einer gespeicherten MP3-Datei zurück.

import os import httpx from pathlib import Path from dotenv import load_dotenv load_dotenv () API_KEY = os. getenv ( " ELEVENLABS_API_KEY " ) BASE_URL = " https://api.elevenlabs.io/v1 " async def synthesize ( text: str, voice_id: str = " EXAVITQu4vr4xnSDxMaL ", # Standardstimme (Rachel) output_path: Path = Path ( " output.mp3 " ), ) -> Path: 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 ": 0.75, " similarity_boost ": 0.75, }, } async with httpx. AsyncClient ( timeout = 30.0 ) as client: response = await client. post ( url, json = payload, headers = headers ) response. raise_for_status () # Die API liefert rohe Audiobytes (MP3) als Stream output_path. write_bytes ( response. content ) return output_path Was passiert hier?

Experimentieren Sie ruhig – ein höherer stability-Wert macht die Stimme monotoner, während ein höherer similarity_boost-Wert sie näher an die Referenzstimme heranbringt.

from pydub import AudioSegment from pydub.playback import play def play_audio ( file_path: Path ): audio = AudioSegment. from_file ( file_path, format = " mp3 " ) play ( audio ) 5️⃣ Alles Zusammensetzen import asyncio from pathlib import Path async def main (): text = ( " Hallo, liebe Entwicklerin, lieber Entwickler! " " Mit ElevenLabs können Sie jede Zeichenkette in eine natürlich klingende Stimme verwandeln. " ) output_file = Path ( " speech.mp3 " ) print ( " Sprachausgabe wird erzeugt… " ) await synthesize ( text, output_path = output_file ) print ( f " Gespeichert unter { output_file } " ) print ( " Wiedergabe läuft… " ) play_audio ( output_file ) if __name__ == " __main__ ": asyncio. run ( main ()) Führen Sie das Skript aus:

python tts_demo.py Sie sollten nun die Phrase in einer klaren, menschenähnlichen Stimme hören. 🎉

ElevenLabs bietet außerdem Voice Cloning an – Sie können einige Minuten Aufnahmen eines Sprechers hochladen und eine eigene Voice-ID generieren. Der Ablauf ist Folgender:

Hier ist ein kurzes curl-Beispiel zum Hochladen einer Probe (ersetzen Sie YOUR_API_KEY und sample.wav durch Ihre eigenen Werte):

curl -X POST "https://api.elevenlabs.io/v1/voices/add" \ -H "xi-api-key: YOUR_API_KEY" \ -F "name=MyCustomVoice" \ -F "files[]=@sample.wav" Die Antwort enthält:

{ "voice_id": "abc123def456", "name": "MyCustomVoice", "preview_url": "https://..." } Übergeben Sie nun einfach "abc123def456" als voice_id an synthesize, und Sie hören Ihre Stimme den Text vorlesen. Das ist ein echter Game-Changer für personalisierte Assistenten, Hörbücher und Synchronisationen.

ElevenLabs setzt ein Anfragenlimit pro Minute fest, das von Ihrem Tarif abhängt. Wenn Sie es überschreiten, erhalten Sie die Antwort 429 Too Many Requests. Eine einfache Retry-Strategie kann Ihre Anwendung reibungslos laufen lassen:

import time async def safe_synthesize ( * args, ** kwargs ): retries = 3 backoff = 2 for attempt in range ( retries ): try: return await synthesize ( * args, ** kwargs ) except httpx. HTTPStatusError as exc: if exc. response. status_code == 429 and attempt < retries - 1: wait = backoff ** attempt print ( f " Rate limit erreicht, warte { wait } s… " ) time. sleep ( wait ) continue raise Umschließen Sie Ihre Aufrufe mit await safe_synthesize, um bei Drosselung automatisch mit wartezeitbasiertem Backoff zu arbeiten.

Wenn Sie diese TTS-Funktion als Micro-Service bereitstellen möchten, eignen sich Flask oder FastAPI hervorragend:

from fastapi import FastAPI, Body from fastapi.responses import FileResponse app = FastAPI () @app.post ( " /speak " ) async def speak ( text: str = Body): out_file = await safe_synthesize ( text ) return FileResponse ( out_file, media_type = " audio/mpeg " ) Deployen Sie alles auf Render, Fly.io oder eine beliebige Container-Plattform, und Sie haben einen HTTP-Endpunkt, der jede Zeichenkette auf Abruf in Sprache umwandelt.

Sie verfügen nun über eine voll funktionsfähige Python-Text-to-Speech-Anwendung, die auf ElevenLabs basiert. Von einer schnellen Demo über einen in der Cloud gehosteten Micro-Service bis hin zu einem eigenen Voice-Clone ist die API flexibel genug für die meisten Entwickler-Workflows.

Probieren Sie es aus, experimentieren Sie mit den Stimmeinstellungen und trainieren Sie vielleicht sogar eine Stimme, die wie Ihre klingt. Die Möglichkeiten werden nur durch Ihre Vorstellungskraft (und das API-Kontingent) begrenzt.

Bereit, Ihrer nächsten Projektidee natürliche Sprache zu verleihen? Testen Sie ElevenLabs noch heute über den Affiliate-Link: https://try.elevenlabs.io/kr07zfuqn1bp – Sie erhalten sofortigen Zugriff auf die API und ein großzügiges, kostenloses Kontingent, um direkt loszulegen. Viel Spaß beim Programmieren!

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

If you’ve ever built a chatbot, an accessibility feature, or a voice‑enabled game, you know that a natural‑sounding voice can turn a static experience into something engaging and human‑like. Modern TTS engines are no longer limited to robotic monotones – they can capture emotion, intonation, and even mimic a specific speaker’s style.

That’s where ElevenLabs shines. Their API delivers high‑quality neural voices that are easy to integrate, and the pricing model works well for both hobby projects and production apps. In this post we’ll walk through building a simple Python app that sends text to ElevenLabs, receives an audio file, and plays it back. By the end you’ll have a reusable script you can drop into any project.

Keep this token secret – treat it like a password.

pip install httpx python-dotenv pydub Enter fullscreen mode Exit fullscreen mode httpx – a modern async HTTP client. python-dotenv – loads environment variables from a.env file. pydub – convenient for playing or converting the returned MP3. (You’ll also need ffmpeg installed on your system; on macOS you can use brew install ffmpeg, on Ubuntu sudo apt-get install ffmpeg.) Create a.env file in your project root:

ELEVENLABS_API_KEY=your_api_key_here Enter fullscreen mode Exit fullscreen mode 3️⃣ The Core TTS Function Below is a minimal async function that talks to ElevenLabs. It accepts the text you want spoken, the voice ID (we’ll use the default “Rachel” for now), and returns the path to a saved MP3 file.

import os import httpx from pathlib import Path from dotenv import load_dotenv load_dotenv () API_KEY = os. getenv ( " ELEVENLABS_API_KEY " ) BASE_URL = " https://api.elevenlabs.io/v1 " async def synthesize ( text: str, voice_id: str = " EXAVITQu4vr4xnSDxMaL ", # default voice (Rachel) output_path: Path = Path ( " output.mp3 " ), ) -> Path: 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 ": 0.75, " similarity_boost ": 0.75, }, } async with httpx. AsyncClient ( timeout = 30.0 ) as client: response = await client. post ( url, json = payload, headers = headers ) response. raise_for_status () # The API streams raw audio bytes (MP3) output_path. write_bytes ( response. content ) return output_path Enter fullscreen mode Exit fullscreen mode What’s happening?

Feel free to experiment – a higher stability makes the voice more monotone, while a higher similarity_boost pushes it toward the reference voice.

from pydub import AudioSegment from pydub.playback import play def play_audio ( file_path: Path ): audio = AudioSegment. from_file ( file_path, format = " mp3 " ) play ( audio ) Enter fullscreen mode Exit fullscreen mode 5️⃣ Putting It All Together import asyncio from pathlib import Path async def main (): text = ( " Hello, fellow developer! " " With ElevenLabs, you can turn any string into a natural‑sounding voice. " ) output_file = Path ( " speech.mp3 " ) print ( " Generating speech… " ) await synthesize ( text, output_path = output_file ) print ( f " Saved to { output_file } " ) print ( " Playing back… " ) play_audio ( output_file ) if __name__ == " __main__ ": asyncio. run ( main ()) Enter fullscreen mode Exit fullscreen mode Run the script:

python tts_demo.py Enter fullscreen mode Exit fullscreen mode You should hear the phrase spoken in a clear, human‑like voice. 🎉

ElevenLabs also offers voice cloning – you can upload a few minutes of a speaker’s recordings and generate a custom voice ID. The workflow is:

Here’s a quick curl example for uploading a sample (replace YOUR_API_KEY and sample.wav with your values):

curl -X POST "https://api.elevenlabs.io/v1/voices/add" \ -H "xi-api-key: YOUR_API_KEY" \ -F "name=MyCustomVoice" \ -F "files[]=@sample.wav" Enter fullscreen mode Exit fullscreen mode The response contains:

{ "voice_id": "abc123def456", "name": "MyCustomVoice", "preview_url": "https://..." } Enter fullscreen mode Exit fullscreen mode Now just pass "abc123def456" as the voice_id to synthesize and you’ll hear your voice reading the text. This is a game‑changer for personalized assistants, audiobooks, and dubbing.

ElevenLabs enforces a per‑minute request quota based on your plan. If you exceed it, you’ll receive a 429 Too Many Requests response. A simple retry strategy can keep your app smooth:

import time async def safe_synthesize ( * args, ** kwargs ): retries = 3 backoff = 2 for attempt in range ( retries ): try: return await synthesize ( * args, ** kwargs ) except httpx. HTTPStatusError as exc: if exc. response. status_code == 429 and attempt < retries - 1: wait = backoff ** attempt print ( f " Rate limited, sleeping { wait } s… " ) time. sleep ( wait ) continue raise Enter fullscreen mode Exit fullscreen mode Wrap your calls with await safe_synthesize to automatically back‑off on throttling.

If you want to expose this TTS capability as a micro‑service, Flask or FastAPI work nicely:

from fastapi import FastAPI, Body from fastapi.responses import FileResponse app = FastAPI () @app.post ( " /speak " ) async def speak ( text: str = Body): out_file = await safe_synthesize ( text ) return FileResponse ( out_file, media_type = " audio/mpeg " ) Enter fullscreen mode Exit fullscreen mode Deploy to Render, Fly.io, or any container platform, and you’ll have an HTTP endpoint that turns any string into speech on demand.

You now have a fully functional Python text‑to‑speech app powered by ElevenLabs. From a quick demo to a cloud‑hosted micro‑service or a custom voice clone, the API is flexible enough to fit most developer workflows.

Give it a spin, experiment with voice settings, and maybe even train a voice that sounds like you. The possibilities are only limited by your imagination (and the API quota).

Ready to bring natural speech to your next project? Try ElevenLabs today with the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp – you’ll get instant access to the API and a generous free tier to start building right away. Happy coding!

Quelle: dev.to (dev.to). Original öffnen