如何使用 ElevenLabs API 建立語音留言生成器
Build a Voicemail Generator with ElevenLabs API
文章示範如何使用 ElevenLabs API,根據來電者資料生成個人化語音留言,並輸出可供電話系統使用的 MP3。示例提供 Python Flask 和 JavaScript Express 實作,接收包含 name、company 和 purpose 的 JSON,並支援使用公眾語音或自有複製語音。
Why a Voicemail Generator?
Ever needed a quick, professional-sounding voicemail for a demo, a test environment, or even a personal project? Manually recording each message can be a pain, especially when you need multiple variations or languages. This is where text‑to‑speech (TTS) shines: you feed in the script, and the service spits out an audio file that sounds like a real person.
In the past, TTS sounded robotic. Today, thanks to neural voice models, you can get natural, expressive speech that even mimics a specific voice style. In this article we’ll build a tiny “voicemail generator” that takes a JSON payload of caller information, renders a personalized greeting with a chosen voice, and saves the result as an MP3 ready to upload to your telephony platform.
The star of the show is the ElevenLabs API – a powerful, developer‑friendly service that delivers high‑quality voice cloning and TTS. You can sign up via this affiliate link and get a free quota to experiment: https://try.elevenlabs.io/kr07zfuqn1bp
Architecture Overview
+-----------------+ +--------------------+ +-------------------+
| Front‑end UI | (POST) | Flask / Express | (GET) | ElevenLabs TTS |
| (optional) |--------->| API Wrapper |--------->| REST Endpoint |
+-----------------+ +--------------------+ +-------------------+
|
v
+-----------------+
| MP3 file saved |
+-----------------+
-
Input – a JSON object with
name,company, andpurpose. - Backend – a lightweight Python (Flask) or Node.js (Express) server that formats the script and calls ElevenLabs.
- Output – an MP3 file stored locally (or in cloud storage) that you can attach to any voicemail system.
Feel free to pick the language you’re most comfortable with; we’ll provide both Python and JavaScript examples, plus a raw curl call for quick testing.
Getting Started with ElevenLabs
First, grab an API key from your ElevenLabs dashboard. The key is a simple string you’ll pass as a header (xi-api-key). Keep it secret – treat it like any other credential.
# Example of checking your quota
curl -H "xi-api-key: YOUR_API_KEY" \
https://api.elevenlabs.io/v1/user
If you don’t have an account yet, sign up here and get instant access: https://try.elevenlabs.io/kr07zfuqn1bp
Python Implementation (Flask)
1️⃣ Install dependencies
pip install flask requests python-dotenv
Create a .env file to store your secret key:
ELEVENLABS_API_KEY=your_api_key_here
2️⃣ The Flask app
# app.py
import os
import uuid
from flask import Flask, request, jsonify, send_file
import requests
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("ELEVENLABS_API_KEY")
ELEVEN_ENDPOINT = "https://api.elevenlabs.io/v1/text-to-speech"
app = Flask(__name__)
def build_script(data):
"""Turn incoming JSON into a friendly voicemail script."""
name = data.get("name", "Valued Customer")
company = data.get("company", "our company")
purpose = data.get("purpose", "leave a message")
return (
f"Hi {name}, this is {company}. "
f"We're calling because you wanted to {purpose}. "
"Please call us back at your earliest convenience. "
"Thank you!"
)
def synthesize_text(text, voice_id="EXAVITQu4vr4xnSDxMaL"):
"""Call ElevenLabs TTS and return raw audio bytes."""
url = f"{ELEVEN_ENDPOINT}/{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}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.content
@app.route("/voicemail", methods=["POST"])
def generate_voicemail():
data = request.json
script = build_script(data)
audio_bytes = synthesize_text(script)
filename = f"voicemail_{uuid.uuid4().hex}.mp3"
with open(filename, "wb") as f:
f.write(audio_bytes)
return send_file(filename, as_attachment=True)
if __name__ == "__main__":
app.run(debug=True)
How it works
-
/voicemailreceives a JSON payload. -
build_scriptcreates a natural‑sounding message. -
synthesize_texttalks to ElevenLabs (thevoice_idcan be any of the public voices or a cloned voice you own). - The MP3 is written to disk and sent back to the client.
3️⃣ Test it with curl
curl -X POST http://127.0.0.1:5000/voicemail \
-H "Content-Type: application/json" \
-d '{"name":"Alice","company":"Acme Corp","purpose":"discuss your order"}' \
--output alice_voicemail.mp3
You should now have alice_voicemail.mp3 ready to drop into any voicemail system.
JavaScript Implementation (Express)
If you prefer Node, here’s a minimal Express version.
1️⃣ Install packages
npm init -y
npm install express axios dotenv
Create a .env file:
ELEVENLABS_API_KEY=your_api_key_here
2️⃣ The server
// server.js
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const app = express();
app.use(express.json());
const ELEVEN_ENDPOINT = 'https://api.elevenlabs.io/v1/text-to-speech';
const API_KEY = process.env.ELEVENLABS_API_KEY;
const DEFAULT_VOICE = 'EXAVITQu4vr4xnSDxMaL';
function buildScript({ name = 'Friend', company = 'our team', purpose = 'reach out' }) {
return `Hey ${name}, this is ${company}. We wanted to ${purpose}. Please give us a call back when you can. Thanks!`;
}
async function synthesize(text, voiceId = DEFAULT_VOICE) {
const url = `${ELEVEN_ENDPOINT}/${voiceId}`;
const headers = {
'xi-api-key': API_KEY,
'Content-Type': 'application/json',
};
const payload = {
text,
model_id: 'eleven_monolingual_v1',
voice_settings: { stability: 0.7, similarity_boost: 0.8 },
};
const { data } = await axios.post(url, payload, { headers, responseType: 'arraybuffer' });
return data;
}
app.post('/voicemail', async (req, res) => {
try {
const script = buildScript(req.body);
const audio = await synthesize(script);
const filename = `voicemail_${uuidv4()}.mp3`;
fs.writeFileSync(filename, audio);
res.download(filename, () => fs.unlinkSync(filename));
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to generate voicemail' });
}
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
3️⃣ Quick test
curl -X POST http://localhost:3000/voicemail \
-H "Content-Type: application/json" \
-d '{"name":"Bob","company":"Beta Ltd","purpose":"confirm your appointment"}' \
--output bob_voicemail.mp3
You’ll hear a crisp, human‑like voice saying the custom message.
Tweaking Voice Settings
ElevenLabs lets you adjust two main knobs:
| Setting | Range | What it does |
|---|---|---|
stability |
0‑1 | Controls how consistent the voice sounds across sentences. Lower values add more “natural” variance. |
similarity_boost |
0‑1 | Pushes the output closer to the reference voice (useful for cloned voices). |
Play around with these values until the voicemail feels just right for your brand. For example, a corporate greeting might benefit from higher stability, while a friendly “hey there” could use a bit more variance.
Deploying to Production
- Environment variables – store the API key in a secret manager (AWS Secrets Manager, Vercel env vars, etc.).
- Rate limiting – ElevenLabs free tier has a request cap; add a simple counter or use a queue if you expect heavy traffic.
- Storage – Instead of writing to disk, stream the bytes directly to S3, Azure Blob, or Google Cloud Storage, then return a signed URL.
- HTTPS – Always serve your endpoint over TLS, especially when handling personal data like caller names.
Going Further
- Voice cloning – Upload a few minutes of a real person’s voice to ElevenLabs, then generate voicemail in their exact timbre. Perfect for creating a “virtual receptionist.”
-
Multilingual support – ElevenLabs supports many languages; just set the appropriate
model_idand feed the script in the target language. -
Dynamic SSML – If you need pauses or emphasis, pass SSML tags in the
textfield. The API respects<break>and<emphasis>tags.
Wrap‑up
You now have a complete, end‑to‑end voicemail generator powered by a state‑of‑the‑art TTS engine. The core idea is simple: accept structured data, turn it into a friendly script, and let ElevenLabs do the heavy lifting of sounding human. With just a few lines of code you can replace manual recordings, automate onboarding calls, or even build a “talking” FAQ bot.
Ready to give it a spin? Grab your free ElevenLabs credits here and start generating lifelike voicemails today: https://try.elevenlabs.io/kr07zfuqn1bp
Happy coding! 🚀
來源:DEV Community · dev.to