Why a Voicemail Generator?
Ever missed a call and wished you could send a personalized voice note instead of a bland text? With modern text‑to‑speech (TTS) services you can turn any string of text into a natural‑sounding voicemail that feels like it was recorded by a real person. In this post we’ll build a tiny “voicemail generator” that:
- Takes a caller’s name, reason for the call, and a custom message.
- Sends the combined script to the ElevenLabs API (the most realistic voice cloning platform on the market today).
- Saves the resulting audio file so you can attach it to an email, SMS, or even a phone‑system webhook.
You’ll see the whole flow in Python, a quick JavaScript example, and a one‑liner curl command for those who love the terminal.
Pro tip: Sign up through this affiliate link to get free credits and a quick start guide: ElevenLabs.
Prerequisites
| What you need | Why |
|---|---|
| Python 3.8+ (or Node.js) | To run the sample scripts |
| An ElevenLabs API key | Authenticates your requests |
ffmpeg (optional) |
Convert the returned MP3 to WAV if your voicemail system needs it |
| Basic knowledge of HTTP | The API is just a REST endpoint |
Grab an API key from the ElevenLabs dashboard after signing up via the link above. Keep it safe – treat it like a password.
Step 1: Craft the Voicemail Script
First, let’s build the text that will be spoken. A simple function can concatenate the pieces you receive from a front‑end form:
def build_script(caller_name: str, reason: str, custom_msg: str) -> str:
"""
Returns a ready‑to‑speak voicemail script.
"""
greeting = f"Hello {caller_name},"
body = f"This is a reminder about {reason}."
closing = f"Message: {custom_msg}"
signoff = "Thank you, and have a great day!"
return " ".join([greeting, body, closing, signoff])
Calling build_script("Alex", "your upcoming appointment", "please arrive 10 minutes early.") yields:
Hello Alex, This is a reminder about your upcoming appointment. Message: please arrive 10 minutes early. Thank you, and have a great day!
Feel free to add SSML tags (e.g., <break time="500ms"/>) if you need extra pauses.
Step 2: Call the ElevenLabs TTS Endpoint (Python)
The core of the generator is a POST request to ElevenLabs’ v1/text-to-speech/{voice_id} endpoint. Below is a minimal, production‑ready wrapper:
import os
import requests
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
VOICE_ID = "EXAVITQu4vr4xnSDxMaL" # Default “Rachel” voice – pick any from your dashboard
def generate_voicemail(script: str, output_path: str = "voicemail.mp3"):
url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
headers = {
"xi-api-key": ELEVENLABS_API_KEY,
"Content-Type": "application/json"
}
payload = {
"text": script,
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85
}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status() # Will raise an HTTPError if something went wrong
# The API returns raw audio bytes (MP3 by default)
with open(output_path, "wb") as f:
f.write(response.content)
print(f"✅ Voicemail saved to {output_path}")
# Example usage
if __name__ == "__main__":
script = build_script(
caller_name="Alex",
reason="your upcoming appointment",
custom_msg="please arrive 10 minutes early."
)
generate_voicemail(script)
What’s happening under the hood?
-
voice_id– each voice you create (or the default ones) gets a unique ID. Pick the one that best matches your brand’s tone. -
model_id–eleven_monolingual_v1is the current high‑quality English model. -
stability/similarity_boost– tweak these to make the voice sound more consistent or more expressive.
If you need a different audio format, add the output_format field ("wav" or "mp3"). The API will honor it automatically.
Step 3: Quick JavaScript (Fetch) Alternative
Sometimes you’re working in a serverless function or a front‑end that can safely call your own backend. Here’s a Node.js snippet using the native fetch API (available in recent Node versions):
import fetch from "node-fetch";
import { writeFile } from "fs/promises";
const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;
const VOICE_ID = "EXAVITQu4vr4xnSDxMaL";
async function generateVoicemail(script, outputFile = "voicemail.mp3") {
const url = `https://api.elevenlabs.io/v1/text-to-speech/${VOICE_ID}`;
const payload = {
text: script,
model_id: "eleven_monolingual_v1",
voice_settings: { stability: 0.75, similarity_boost: 0.85 },
};
const res = await fetch(url, {
method: "POST",
headers: {
"xi-api-key": ELEVENLABS_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.text();
throw new Error(`ElevenLabs error: ${err}`);
}
const audioBuffer = await res.buffer();
await writeFile(outputFile, audioBuffer);
console.log(`✅ Saved voicemail to ${outputFile}`);
}
// Example
const script = "Hello Jamie, this is a reminder about your subscription renewal. Please review your account.";
generateVoicemail(script).catch(console.error);
The logic mirrors the Python version—just a different syntax.
Step 4: One‑Liner curl (For Debugging)
When you want to test the API without writing code, a curl command works fine. Replace YOUR_API_KEY and YOUR_VOICE_ID with your actual values.
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/YOUR_VOICE_ID" \
-H "xi-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello Sam, this is a quick check‑in about your order status. Feel free to reply if you have any questions.",
"model_id": "eleven_monolingual_v1",
"voice_settings": { "stability": 0.75, "similarity_boost": 0.85 }
}' \
--output voicemail.mp3
You’ll see a voicemail.mp3 file in the current directory, ready to be attached to any outbound channel.
Step 5: Integrate with Your Phone System
Most cloud telephony platforms (Twilio, Plivo, Nexmo) let you play an MP3 or WAV file via a URL. After generating the voicemail, upload it to a static bucket (e.g., AWS S3, Cloudflare R2) and return the public URL in your webhook response:
# Example Twilio TwiML response
from twilio.twiml.voice_response import VoiceResponse
def twiml_response(audio_url):
resp = VoiceResponse()
resp.play(audio_url)
return str(resp)
Now, when a caller hits your number, the system fetches the freshly generated voice note and plays it back as if you recorded it yourself.
Fine‑Tuning Tips
| Goal | Setting | Suggested Value |
|---|---|---|
| More expressive | stability |
0.55‑0.65 |
| Crystal‑clear diction | similarity_boost |
0.9‑0.95 |
| Shorter pauses | Insert <break time="200ms"/> in SSML |
N/A |
| Different gender | Choose another voice_id from the dashboard |
N/A |
Experiment! The API is cheap enough to spin up a few variations and listen to them side‑by‑side.
Security & Rate Limits
- API Key – Store it in environment variables or secret managers. Never hard‑code it.
-
Rate limits – ElevenLabs allows generous free‑tier usage, but if you hit the limit you’ll receive a
429response. Implement exponential back‑off or batch your calls. - Compliance – If you clone a real person’s voice, make sure you have their consent. The platform enforces a “voice ownership” policy to keep things ethical.
Wrap‑Up
You now have a complete pipeline:
- Collect caller details.
- Build a natural‑language script.
- Send it to ElevenLabs for ultra‑realistic speech synthesis.
- Store the audio file and serve it through your telephony provider.
All of this can be wrapped in a serverless function, a Flask/Django view, or a tiny Node.js microservice. The result is a personalized voicemail experience that feels human, scales automatically, and costs only a few cents per minute of audio.
Ready to give your users a voice they’ll recognize? Grab your free credits and start building with the industry‑leading TTS platform today: ElevenLabs. Happy coding!
Top comments (0)