Why Voice Notifications Matter
If you’ve ever built a monitoring dashboard, a home‑automation hub, or a customer‑support bot, you know that a timely alert can be the difference between a smooth experience and a frantic scramble. Text alerts are great, but they’re limited to screens and keyboards. Adding a spoken voice layer lets you reach users hands‑free, anywhere, and often faster.
Enter modern text‑to‑speech (TTS) platforms. They’ve gone from robotic monotones to natural‑sounding, expressive speech that can even mimic a specific voice. With a few lines of code you can turn any string into an audio file, stream it to a speaker, or push it straight to a phone app. In this post we’ll walk through building a simple voice notification system using ElevenLabs, a service that offers high‑quality TTS and voice cloning with an easy‑to‑use API.
TL;DR – By the end of this guide you’ll have a Python script that watches a folder for new JSON alerts, converts the alert text into speech with ElevenLabs, and plays the result on your local machine.
What Makes ElevenLabs a Good Fit
- Natural voice quality – Their neural models produce near‑human prosody, making notifications pleasant rather than annoying.
- Voice cloning – Want a brand‑specific voice? Upload a few minutes of audio and ElevenLabs will generate a custom voice that sounds like yours.
- Simple REST API – No need to wrestle with OAuth flows; a single API key is enough for most use‑cases.
You can sign up and get your API key here: https://try.elevenlabs.io/kr07zfuqn1bp.
Architecture Overview
+-------------------+ +-------------------+ +-------------------+
| Alert Producer | --> | Watcher Service | --> | ElevenLabs TTS |
| (e.g. sensor, API) | | (Python script) | | API |
+-------------------+ +-------------------+ +-------------------+
|
v
+-------------------+
| Audio Playback |
+-------------------+
-
Alert Producer – Any system that can emit a JSON payload with a
messagefield. - Watcher Service – A lightweight Python script that watches a directory (or a message queue) for new alerts.
-
ElevenLabs TTS – The script sends the
messageto ElevenLabs and receives an MP3/OGG stream. - Audio Playback – The script plays the audio locally (or forwards it to a speaker device).
Getting Started
1. Create an ElevenLabs Account
Visit the sign‑up page: https://try.elevenlabs.io/kr07zfuqn1bp. After confirming your email you’ll land on the dashboard where you can generate an API key. Keep that key handy; you’ll need it in the code.
2. Install Dependencies
# Create a virtual environment (optional but recommended)
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install required packages
pip install watchdog requests pydub simpleaudio
- watchdog – watches a folder for new files.
- requests – makes HTTP calls to the ElevenLabs API.
- pydub – handles audio conversion (ElevenLabs returns MP3).
- simpleaudio – plays the resulting WAV buffer instantly.
3. The Core Script
Create a file called voice_notifier.py:
import os
import json
import time
import base64
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from pydub import AudioSegment
import simpleaudio as sa
# ------------------- Configuration -------------------
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") # set in env or replace directly
VOICE_ID = "EXAVITQu4vr4xnSDxMaL" # default "Rachel" voice – change if you have a custom clone
OUTPUT_DIR = "alerts"
# ----------------------------------------------------
class AlertHandler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory or not event.src_path.endswith(".json"):
return
try:
with open(event.src_path, "r", encoding="utf-8") as f:
payload = json.load(f)
text = payload.get("message", "")
if not text:
print("⚠️ No 'message' field in alert.")
return
print(f"🔔 New alert: {text}")
audio_bytes = synthesize(text)
play_audio(audio_bytes)
# Optionally move processed file
os.rename(event.src_path, event.src_path + ".processed")
except Exception as e:
print(f"❌ Error handling alert: {e}")
def synthesize(text: str) -> bytes:
"""Send text to ElevenLabs and return raw audio bytes (MP3)."""
url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
headers = {
"xi-api-key": ELEVENLABS_API_KEY,
"Content-Type": "application/json"
}
data = {
"text": text,
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85
}
}
resp = requests.post(url, json=data, headers=headers)
resp.raise_for_status()
return resp.content # MP3 bytes
def play_audio(mp3_bytes: bytes):
"""Convert MP3 to WAV (in‑memory) and play it."""
audio = AudioSegment.from_file(io.BytesIO(mp3_bytes), format="mp3")
wav_data = audio.raw_data
play_obj = sa.play_buffer(
wav_data,
num_channels=audio.channels,
bytes_per_sample=audio.sample_width,
sample_rate=audio.frame_rate,
)
play_obj.wait_done()
if __name__ == "__main__":
if not ELEVENLABS_API_KEY:
raise RuntimeError("Set ELEVENLABS_API_KEY environment variable first.")
os.makedirs(OUTPUT_DIR, exist_ok=True)
event_handler = AlertHandler()
observer = Observer()
observer.schedule(event_handler, OUTPUT_DIR, recursive=False)
observer.start()
print(f"👂 Watching '{OUTPUT_DIR}' for new alerts...")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
How It Works
-
Folder Watch –
watchdogtriggerson_createdwhenever a new JSON file lands inalerts/. -
Parse Alert – We read the
messagefield. -
Call ElevenLabs – The
synthesizefunction POSTs tohttps://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}with the API key. -
Play Audio – The MP3 response is turned into a
pydub.AudioSegment, then streamed to the speakers viasimpleaudio.
Tip: If you prefer a custom voice, replace
VOICE_IDwith the ID you receive after cloning a voice on the ElevenLabs dashboard.
4. Test It Out
- Export your API key:
export ELEVENLABS_API_KEY="your‑api‑key‑here"
- Run the script:
python voice_notifier.py
- Drop a test alert into the
alerts/folder:
{
"message": "Server CPU usage is above 90 percent."
}
Save it as cpu_alert.json. You should hear the spoken notification within a second.
Extending the System
- Push to Mobile – Use a service like Twilio to send the MP3 as an MMS, or integrate with Firebase Cloud Messaging for push notifications that play the audio client‑side.
-
Multiple Voices – Store a mapping of alert types to different
VOICE_IDs (e.g., “error” = a stern voice, “info” = a friendly voice). - Queue Integration – Swap the folder watcher for a RabbitMQ or AWS SQS consumer if you need higher reliability.
-
Webhooks – Expose a tiny Flask endpoint that accepts POSTed JSON, calls
synthesize, and returns a URL to the generated audio.
All of these patterns use the same core call to ElevenLabs, which means you can keep your code DRY and your voice quality consistent.
Common Pitfalls
| Issue | Why It Happens | Fix |
|---|---|---|
| Audio is garbled | Wrong content‑type or corrupted MP3 bytes. | Ensure Content-Type: application/json and use resp.content directly. |
| Rate‑limit errors | Exceeding the free tier’s request quota. | Batch alerts or upgrade your plan on ElevenLabs. |
| Voice cloning not sounding right | Uploaded sample is too short or noisy. | Provide at least 30 seconds of clean speech; the more varied the dataset, the better. |
| Script crashes on malformed JSON | Unexpected file format. | Wrap json.load in a try/except and log the offending file. |
Deploying to Production
When you move from a local script to a production service, consider:
-
Containerization – Dockerize the script with a lightweight
python:3.11-slimimage. -
Secret Management – Store
ELEVENLABS_API_KEYin Vault, AWS Secrets Manager, or GitHub Actions secrets, not in source code. - Observability – Emit logs to CloudWatch or Loki; add metrics for “alerts processed” and “TTS latency”.
- Scalability – Run multiple instances behind a message queue; ElevenLabs can handle concurrent requests, but respect the per‑minute quota of your plan.
A minimal Dockerfile could look like:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY voice_notifier.py .
ENV OUTPUT_DIR=/data
VOLUME /data
CMD ["python", "voice_notifier.py"]
Build and run:
docker build -t voice-notifier .
docker run -e ELEVENLABS_API_KEY=YOUR_KEY -v $(pwd)/alerts:/data voice-notifier
Now any service that can write a JSON file to the mounted volume will instantly trigger a spoken alert.
Wrap‑Up
Voice notifications are no longer a “nice‑to‑have” experiment; they’re becoming a core part of responsive, accessible applications. With ElevenLabs you get studio‑grade speech without the heavy lifting of training deep‑learning models yourself. The example above shows a complete, production‑ready pipeline in under 100 lines of Python.
Ready to give your alerts a voice?
👉 Try ElevenLabs today: https://try.elevenlabs.io/kr07zfuqn1bp
Add that link to your project, grab an API key, and start turning text into natural‑sounding speech in minutes. Happy coding!
Top comments (0)