ai newsDo., 15. Okt.
EilmeldungMeta and Apple team up to make Muse AI models run better on Macs

Voice-Apps mit ElevenLabs und Twilio bauen

Wer Nutzern individuelle Spracherlebnisse bieten will, kombiniert ElevenLabs' Text-to-Speech mit Twilios programmierbarer Voice-Plattform. Anwendungsbeispiele sind automatisierte Support-Hotlines, interaktives Storytelling oder dynamische Benachrichtigungen.

dev.toDonnerstag 02:18 · 15.10.DE5 Min. Lesezeit
Bild: dev.to

Wenn Sie Ihren Nutzern ein wirklich persönliches Spracherlebnis bieten möchten, etwa bei automatisierten Support-Hotlines, interaktivem Storytelling oder dynamischen Benachrichtigungen, dann ist die Kombination aus ElevenLabs' hochmodernem Text-to-Speech (TTS) und Twilios programmierbarer Sprachplattform eine im Himmel geschlossene Cloud-Ehe.

Gemeinsam können Sie damit eine eigene Stimme on the fly erzeugen und sie direkt in einen laufenden Anruf einspeisen, und das ganze mit nur wenigen Zeilen Code.

Kurzer Tipp: Falls Sie ElevenLabs noch nicht ausprobiert haben, können Sie sich über diesen Affiliate-Link anmelden: https://try.elevenlabs.io/kr07zfuqn1bp – es ist dasselbe Produkt, nur ein bequemer Weg, um loszulegen.

ElevenLabs stellt einen einfachen /v1/text-to-speech/{voice_id} Endpunkt bereit. Hier ist eine minimale Python-Funktion, die einen Prompt sendet und eine URL zur generierten MP3-Datei zurückgibt.

import requests import os ELEVEN_API_KEY = os. getenv ( " ELEVEN_API_KEY " ) VOICE_ID = " EXAVITQu4vr4xnSDxMaL " # Standardstimme „Rachel“; ersetzen Sie dies durch Ihre geklonte Voice-ID def generate_speech ( text: str ) -> str: url = f " https://api.elevenlabs.io/v1/text-to-speech/ { VOICE_ID } " headers = { " xi-api-key ": ELEVEN_API_KEY, " Content-Type ": " application/json " } payload = { " text ": text, " model_id ": " eleven_monolingual_v1 ", " voice_settings ": { " stability ": 0.75, " similarity_boost ": 0.85 } } resp = requests. post ( url, json = payload, headers = headers ) resp. raise_for_status () # Die API liefert rohe Audio-Bytes zurück; wir speichern sie in einer temporären Datei. filename = f " /tmp/ { hash ( text ) }.mp3 " with open ( filename, " wb " ) as f: f. write ( resp. content ) return f " file:// { filename } " Enter fullscreen mode Exit fullscreen mode Ein paar Dinge sind dabei zu beachten:

Twilio erwartet eine öffentlich erreichbare URL, die eine Mediendatei mit einem unterstützten MIME-Typ zurückgibt (audio/mpeg, audio/wav usw.). Eine kurze Flask-Route kann die Lücke schließen:

from flask import Flask, request, send_file, abort import uuid app = Flask ( __name__ ) # In‑Memory-Map: request_id → lokaler Dateipfad audio_store = {} @app.route ( " /speak ", methods = [ " POST " ]) def speak (): data = request. json if not data or " text " not in data: abort ( 400, " Missing ' text ' field " ) # Sprachausgabe generieren und eine Referenz behalten audio_url = generate_speech ( data [ " text " ]) request_id = str ( uuid. uuid4 ()) audio_store [ request_id ] = audio_url. replace ( " file:// ", "" ) # Eine TwiML-Antwort zurückgeben, die Twilio mitteilt, wo es die Audiodatei abholen kann twiml = f """ <?xml version= " 1.0 " encoding= " UTF-8 "?> <Response> <Play> { request. host_url } audio/ { request_id } </Play> </Response> """ return twiml, 200, { " Content-Type ": " application/xml " } @app.route ( " /audio/<uid> " ) def serve_audio ( uid ): path = audio_store. get ( uid ) if not path or not os. path. exists ( path ): abort ( 404 ) return send_file ( path, mimetype = " audio/mpeg " ) Enter fullscreen mode Exit fullscreen mode Wenn Twilio /speak mit einem JSON-Payload wie {"text":"Hello, this is a test!"} aufruft, tut der Endpunkt Folgendes:

Gehen Sie in der Twilio Console zu Phone Numbers → Manage → Active Numbers, wählen Sie Ihre Nummer aus und setzen Sie den Webhook unter Voice & Fax → A CALL COMES IN auf Ihren /speak Endpunkt, zum Beispiel:

https://my‑app.example.com/speak Enter fullscreen mode Exit fullscreen mode Stellen Sie sicher, dass die Anfragemethode POST ist (die Flask-Route erwartet JSON).

Sie können einen Anruf von überall starten, etwa aus Ihrem Backend, einem CLI-Skript oder sogar einer Zapier-Aktion. Hier ist ein einfaches Python-Snippet mit twilio-python:

from twilio.rest import Client import os TWILIO_SID = os. getenv ( " TWILIO_ACCOUNT_SID " ) TWILIO_TOKEN = os. getenv ( " TWILIO_AUTH_TOKEN " ) client = Client ( TWILIO_SID, TWILIO_TOKEN ) call = client. calls. create ( to = " +15551234567 ", # Zielrufnummer from_ = " +15557654321 ", # Ihre Twilio-Nummer url = " https://my-app.example.com/speak ", # TwiML-Webhook method = " POST ", # Optional: übergeben Sie den vorzulesenden Text als Query-Parameter oder im Body # Twilio wird ihn an Ihren Endpunkt POSTen; dort können Sie ihn auslesen. ) print ( f " Call SID: { call. sid } " ) Enter fullscreen mode Exit fullscreen mode Sobald der Anruf verbunden wird, ruft Twilio den /speak Endpunkt auf, der wiederum ElevenLabs auffordert, das Audio zu generieren, und es dann dem Angerufenen vorspielt.

Wenn Sie Antworten nahezu in Echtzeit benötigen (zum Beispiel einen Chatbot, der sofort antwortet), können Sie das ElevenLabs-Audio direkt über Twilio Media Streams an Twilio streamen. Die Idee ist dabei folgende:

Während die vollständige Implementierung den Rahmen dieses Artikels sprengen würde, sieht das Muster so aus:

<Response> <StartStream name= "myStream" url= "wss://my-app.example.com/stream" /> <Pause length= "1" /> <!-- dem Stream einen Moment geben, um sich zu verbinden --> <Say voice= "alice" > Listening... </Say> </Response> Enter fullscreen mode Exit fullscreen mode Ihr WebSocket-Handler würde den vorzulesenden Text empfangen, ElevenLabs über den Streaming-Endpunkt ( /v1/text-to-speech/{voice_id}/stream ) aufrufen und jeden Chunk an Twilio weiterleiten. Das ergibt eine Latenz von unter einer Sekunde und fühlt sich wirklich konversationell an.

Unten sehen Sie einen minimalen End-to-End-Ablauf als Diagramm:

User → (Dial) Twilio → (POST) /speak → generate_speech() → ElevenLabs API ↑ | | v ←——————— <Play> audio URL ←——————— (MP3 speichern & ausliefern) Enter fullscreen mode Exit fullscreen mode Mit der Flask-App, dem Twilio-Webhook und dem kleinen twilio-python-Client-Snippet haben Sie eine voll funktionsfähige Voice-AI-Pipeline, die sich erweitern lässt für:

All das ist mit wenigen Dutzend Zeilen Code und der mächtigen Kombination aus ElevenLabs und Twilio möglich.

Die Hürde für den Bau hochwertiger Sprachanwendungen war noch nie so niedrig. Holen Sie sich einen API-Schlüssel, starten Sie einen kleinen Flask- (oder Express-)Dienst und beginnen Sie zu experimentieren. Falls Sie neugierig darauf sind, wie realistisches Voice Cloning das Engagement steigern kann, probieren Sie ElevenLabs noch heute über diesen Link aus: https://try.elevenlabs.io/kr07zfuqn1bp. Happy Coding!

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

Original (Englisch) anzeigen

If you’ve ever wanted to give your users a truly personal voice experience—think automated support lines, interactive storytelling, or dynamic notifications—pairing ElevenLabs ’ state‑of‑the‑art text‑to‑speech (TTS) with Twilio ’s programmable voice platform is a match made in the cloud.

Together, you can generate a custom voice on the fly and pipe it straight into a live call, all with just a few lines of code.

Quick tip: If you haven’t tried ElevenLabs yet, you can sign up through this affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp – it’s the same product, just a convenient way to get started.

ElevenLabs exposes a simple /v1/text-to-speech/{voice_id} endpoint. Here’s a minimal Python function that sends a prompt and returns a URL to the generated MP3.

import requests import os ELEVEN_API_KEY = os. getenv ( " ELEVEN_API_KEY " ) VOICE_ID = " EXAVITQu4vr4xnSDxMaL " # default “Rachel” voice; replace with your cloned voice ID def generate_speech ( text: str ) -> str: url = f " https://api.elevenlabs.io/v1/text-to-speech/ { VOICE_ID } " headers = { " xi-api-key ": ELEVEN_API_KEY, " Content-Type ": " application/json " } payload = { " text ": text, " model_id ": " eleven_monolingual_v1 ", " voice_settings ": { " stability ": 0.75, " similarity_boost ": 0.85 } } resp = requests. post ( url, json = payload, headers = headers ) resp. raise_for_status () # The API returns raw audio bytes; we’ll store them in a temporary file. filename = f " /tmp/ { hash ( text ) }.mp3 " with open ( filename, " wb " ) as f: f. write ( resp. content ) return f " file:// { filename } " Enter fullscreen mode Exit fullscreen mode A few things to note:

Twilio expects a publicly reachable URL that returns a media file with a supported MIME type ( audio/mpeg, audio/wav, etc.). A quick Flask route can bridge the gap:

from flask import Flask, request, send_file, abort import uuid app = Flask ( __name__ ) # In‑memory map: request_id → local file path audio_store = {} @app.route ( " /speak ", methods = [ " POST " ]) def speak (): data = request. json if not data or " text " not in data: abort ( 400, " Missing ' text ' field " ) # Generate speech and keep a reference audio_url = generate_speech ( data [ " text " ]) request_id = str ( uuid. uuid4 ()) audio_store [ request_id ] = audio_url. replace ( " file:// ", "" ) # Return a TwiML response that tells Twilio where to fetch the audio twiml = f """ <?xml version= " 1.0 " encoding= " UTF-8 "?> <Response> <Play> { request. host_url } audio/ { request_id } </Play> </Response> """ return twiml, 200, { " Content-Type ": " application/xml " } @app.route ( " /audio/<uid> " ) def serve_audio ( uid ): path = audio_store. get ( uid ) if not path or not os. path. exists ( path ): abort ( 404 ) return send_file ( path, mimetype = " audio/mpeg " ) Enter fullscreen mode Exit fullscreen mode When Twilio hits /speak with a JSON payload like {"text":"Hello, this is a test!"}, the endpoint:

In the Twilio Console, go to Phone Numbers → Manage → Active Numbers, select your number, and set the Voice & Fax → A CALL COMES IN webhook to point at your /speak endpoint, e.g.:

https://my‑app.example.com/speak Enter fullscreen mode Exit fullscreen mode Make sure the request method is POST (the Flask route expects JSON).

You can launch a call from anywhere—your backend, a CLI script, or even a Zapier action. Here’s a simple Python snippet using twilio-python:

from twilio.rest import Client import os TWILIO_SID = os. getenv ( " TWILIO_ACCOUNT_SID " ) TWILIO_TOKEN = os. getenv ( " TWILIO_AUTH_TOKEN " ) client = Client ( TWILIO_SID, TWILIO_TOKEN ) call = client. calls. create ( to = " +15551234567 ", # Destination number from_ = " +15557654321 ", # Your Twilio number url = " https://my-app.example.com/speak ", # TwiML webhook method = " POST ", # Optional: pass the text you want spoken as a query param or body # Twilio will POST it to your endpoint; you can read it there. ) print ( f " Call SID: { call. sid } " ) Enter fullscreen mode Exit fullscreen mode When the call connects, Twilio will request the /speak endpoint, which in turn will ask ElevenLabs to generate the audio and then play it back to the callee.

If you need near‑real‑time responses (e.g., a chatbot that replies instantly), you can stream the ElevenLabs audio directly to Twilio using Twilio Media Streams. The idea is:

While the full implementation is beyond the scope of this article, the pattern looks like this:

<Response> <StartStream name= "myStream" url= "wss://my-app.example.com/stream" /> <Pause length= "1" /> <!-- give the stream a moment to connect --> <Say voice= "alice" > Listening... </Say> </Response> Enter fullscreen mode Exit fullscreen mode Your WebSocket handler would receive the text you want spoken, call ElevenLabs with the streaming endpoint ( /v1/text-to-speech/{voice_id}/stream ), and forward each chunk back to Twilio. This yields sub‑second latency and feels truly conversational.

Below is a minimal end‑to‑end flow diagram:

User → (Dial) Twilio → (POST) /speak → generate_speech() → ElevenLabs API ↑ | | v ←——————— <Play> audio URL ←——————— (store & serve MP3) Enter fullscreen mode Exit fullscreen mode With the Flask app, the Twilio webhook, and the tiny twilio-python client snippet, you have a fully functional voice‑AI pipeline that can be extended to:

All of this is possible with a few dozen lines of code and the powerful combination of ElevenLabs and Twilio.

The barrier to building high‑quality voice applications has never been lower. Grab an API key, spin up a tiny Flask (or Express) service, and start experimenting. If you’re curious about how realistic voice cloning can boost engagement, try ElevenLabs today via this link: https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding!

Originaltitel: ElevenLabs + Twilio: Building Voice Call ApplicationsQuelle: dev.to (dev.to). Original öffnen