DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Voice Notification System with ElevenLabs

Introduction

Imagine your app could speak to users in a natural, human‑like voice—whether it’s a reminder, an alert, or a personalized greeting. With modern text‑to‑speech (TTS) APIs, that’s no longer a futuristic fantasy. In this post you’ll learn how to spin up a voice notification system using the powerful ElevenLabs API. We’ll walk through getting an API key, sending a request from Python (and a quick curl example), and wiring it up to a tiny Flask endpoint that can be called from any service.

Pro tip: If you’re looking for a TTS service that delivers high‑fidelity speech and supports voice cloning, ElevenLabs (https://try.elevenlabs.io/kr07zfuqn1bp) is a solid choice. Their free tier is generous enough for prototyping, and the API is straightforward.


What makes ElevenLabs a good fit?

  • Natural‑sounding voices – Deep neural networks trained on thousands of hours of speech produce output that feels human.
  • Voice cloning – Upload a short sample (as little as a minute) and generate speech that mimics a specific speaker. Perfect for branding or personalized messages.
  • Simple REST API – JSON payloads, standard HTTP authentication, and a clear documentation page.

All of that means you can focus on the logic of your notification system rather than wrestling with low‑level audio processing.


Getting started: API key & environment

  1. Sign up at the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp.
  2. Once you��re logged in, navigate to Dashboard → API Keys and create a new key.
  3. Store the key safely. For local development we’ll use an environment variable:
export ELEVENLABS_API_KEY="your_secret_key_here"
Enter fullscreen mode Exit fullscreen mode

You can also add it to a .env file and load it with python-dotenv if you prefer.


A minimal Python client

Below is a tiny wrapper around the ElevenLabs TTS endpoint. It takes plain text, picks a voice, and returns an MP3 file saved to disk.

import os
import requests

ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"
API_KEY = os.getenv("ELEVENLABS_API_KEY")
DEFAULT_VOICE_ID = "EXAVITQu4vr4xnSDxMaL"  # "Rachel" – you can list voices via /v1/voices

def synthesize(text: str, voice_id: str = DEFAULT_VOICE_ID, output_path: str = "output.mp3"):
    url = f"{ELEVENLABS_API_URL}/{voice_id}"
    headers = {
        "xi-api-key": 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.85
        }
    }

    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()

    # The API streams raw audio bytes; write them directly to a file
    with open(output_path, "wb") as f:
        f.write(response.content)
    print(f"✅ Saved speech to {output_path}")

# Example usage
if __name__ == "__main__":
    synthesize("Your meeting starts in five minutes. Please join the conference room.")
Enter fullscreen mode Exit fullscreen mode

How it works

  • Endpoint – POST /v1/text-to-speech/{voice_id} returns an MP3 by default.
  • Model selection – eleven_monolingual_v1 gives the best quality for English; there are multilingual models too.
  • Voice settings – stability controls prosody smoothness, while similarity_boost tweaks how closely the output matches the reference voice (useful for cloned voices).

Run the script, and you’ll have an output.mp3 ready to be played back or attached to a push notification.


Quick curl alternative

If you just need to test the endpoint, a one‑liner works fine:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/EXAVITQu4vr4xnSDxMaL" \
     -H "xi-api-key: $ELEVENLABS_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
           "text": "Your order has shipped and will arrive tomorrow.",
           "model_id": "eleven_monolingual_v1",
           "voice_settings": { "stability": 0.7, "similarity_boost": 0.8 }
         }' \
     --output order_notification.mp3
Enter fullscreen mode Exit fullscreen mode

The --output flag writes the binary audio directly to a file, just like the Python example.


Hooking it up to a Flask endpoint

Most real‑world apps need to trigger voice alerts from a webhook, a cron job, or an internal event. Here’s a tiny Flask service that accepts JSON payloads and returns the generated MP3 as a streaming response.

from flask import Flask, request, send_file, abort
import io
import requests
import os

app = Flask(__name__)

ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"
API_KEY = os.getenv("ELEVENLABS_API_KEY")
DEFAULT_VOICE = "EXAVITQu4vr4xnSDxMaL"

def generate_speech(text, voice_id=DEFAULT_VOICE):
    url = f"{ELEVENLABS_API_URL}/{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.85}
    }
    resp = requests.post(url, json=payload, headers=headers, stream=True)
    resp.raise_for_status()
    return io.BytesIO(resp.content)

@app.route("/notify", methods=["POST"])
def notify():
    data = request.get_json()
    if not data or "message" not in data:
        abort(400, description="JSON body with 'message' field required.")

    voice_id = data.get("voice_id", DEFAULT_VOICE)
    audio_stream = generate_speech(data["message"], voice_id)

    # Flask will set appropriate headers for an MP3 download
    return send_file(
        audio_stream,
        mimetype="audio/mpeg",
        as_attachment=False,
        download_name="notification.mp3"
    )

if __name__ == "__main__":
    app.run(debug=True, port=5000)
Enter fullscreen mode Exit fullscreen mode

Using the endpoint

curl -X POST http://localhost:5000/notify \
     -H "Content-Type: application/json" \
     -d '{"message":"Your backup completed successfully!"}' \
     --output backup_success.mp3
Enter fullscreen mode Exit fullscreen mode

You now have a RESTful voice notification service that can be called from any language or automation platform (Zapier, GitHub Actions, Home Assistant, etc.).


Voice cloning for personalized alerts

ElevenLabs lets you upload a short voice sample and receive a voice_id you can reuse forever. Here’s the flow:

  1. Upload the sample – POST /v1/voices/add with a multipart/form-data payload containing the audio file.
  2. Wait for processing – The response includes a voice_id.
  3. Use the new voice – Pass that voice_id to the /text-to-speech endpoint just like we did above.
def upload_clone(audio_path, name="MyClone"):
    url = "https://api.elevenlabs.io/v1/voices/add"
    headers = {"xi-api-key": API_KEY}
    files = {"audio": open(audio_path, "rb")}
    data = {"name": name}
    resp = requests.post(url, headers=headers, files=files, data=data)
    resp.raise_for_status()
    return resp.json()["voice_id"]
Enter fullscreen mode Exit fullscreen mode

After you’ve created a clone, you can generate personalized notifications such as “Hey John, your coffee is ready!” using the user’s own voice—great for accessibility or brand consistency.


Best practices & gotchas

Area Recommendation
Rate limits Free tier allows ~2000 characters per minute. Batch multiple messages or upgrade if you hit the ceiling.
Audio size The API returns MP3 (~24 KB per 30 seconds). If you need higher fidelity, request wav via the output_format parameter.
Caching For static alerts (e.g., “Your password was changed”), cache the MP3 locally to avoid redundant API calls.
Security Never hard‑code the API key. Use environment variables or a secret manager (AWS Secrets Manager, HashiCorp Vault).
Voice cloning ethics Only clone voices you own or have explicit permission to use. Respect privacy and comply with relevant regulations.

Wrap‑up

You’ve seen how to:

  • Grab an ElevenLabs API key (https://try.elevenlabs.io/kr07zfuqn1bp) and set up your environment.
  • Generate speech with a few lines of Python or a single curl command.
  • Expose a Flask endpoint that turns any textual alert into an instant audio file.
  • (Optionally) clone a custom voice for truly personalized notifications.

All of this can be dropped into a microservice, a serverless function, or even a desktop script. The result is a richer, more engaging user experience that leverages state‑of‑the‑art voice AI.


Ready to give your app a voice?

Head over to ElevenLabs, grab your free API key, and start building the notification system that talks back to your users. The code snippets above are a solid foundation—tweak the voice settings, experiment with different models, and watch your product come alive.

Try ElevenLabs today: https://try.elevenlabs.io/kr07zfuqn1bp 🚀

Top comments (1)

Collapse
 
aichiliai profile image
AI Chili •

Low-latency audio generation with clean fallback handling makes event-driven voice pipelines way less brittle in production. Practical walkthrough!