How to Add AI Voice to Your Django App
Why Add AI Voice to a Django App? If you’ve ever wanted to turn a blog post into an audio article, give a chatbot a natural‑sounding voice, or add accessibility features for visually‑impaired users, text‑to‑speech (TTS
Why Add AI Voice to a Django App?
If you’ve ever wanted to turn a blog post into an audio article, give a chatbot a natural‑sounding voice, or add accessibility features for visually‑impaired users, text‑to‑speech (TTS) is the answer. Modern AI‑driven TTS services can generate lifelike speech in seconds, and many of them even let you clone a custom voice. In this post we’ll walk through a practical way to plug ElevenLabs into a Django project, expose a simple API endpoint, and play the result on the front‑end with a few lines of JavaScript.
TL;DR – Install the ElevenLabs Python SDK, create a Django view that calls the API, serve the audio file, and use the Web Audio API to stream it back to the user.
1. Set Up Your Django Project
If you already have a Django app, skip to the next section. Otherwise, spin up a fresh project:
python -m venv venv
source venv/bin/activate
pip install django
django-admin startproject voice_demo
cd voice_demo
python manage.py startapp tts
Add the new app to INSTALLED_APPS in voice_demo/settings.py:
INSTALLED_APPS = [
# …
"tts",
]
Run migrations and start the dev server to verify everything works:
python manage.py migrate
python manage.py runserver
2. Get an ElevenLabs API Key
Head over to the ElevenLabs platform and sign up for a free tier. Once you’re logged in, locate the API key in the dashboard and copy it – you’ll need it for the next step.
👉 Pro tip: Store the key in an environment variable so you never commit it to source control.
export ELEVENLABS_API_KEY="your-secret-key"
3. Install the ElevenLabs Python SDK
ElevenLabs provides a thin wrapper around their REST API. Install it in your virtual environment:
pip install elevenlabs
You can also call the API directly with curl if you prefer a lower‑level approach – we’ll show both later.
4. Build a Simple TTS Endpoint
Create a view that accepts plain text, sends it to ElevenLabs, and returns the generated audio as an HTTP response.
tts/views.py
import os
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from elevenlabs import generate, set_api_key, save
# Grab the key from the environment
set_api_key(os.getenv("ELEVENLABS_API_KEY"))
@csrf_exempt # For demo purposes; use proper auth in production
def synthesize(request):
if request.method != "POST":
return JsonResponse({"error": "POST required"}, status=405)
data = request.POST
text = data.get("text")
voice_id = data.get("voice_id", "EXAVITQu4vr4xnSDxMaL") # default ElevenLabs voice
if not text:
return JsonResponse({"error": "Missing 'text' field"}, status=400)
# Generate audio bytes (default MP3, 44kHz)
audio = generate(
text=text,
voice=voice_id,
model="eleven_multilingual_v2"
)
# Return as streaming response
response = HttpResponse(audio, content_type="audio/mpeg")
response["Content-Disposition"] = 'attachment; filename="speech.mp3"'
return response
Add the route in tts/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("synthesize/", views.synthesize, name="synthesize"),
]
And include it in the project’s main urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("tts/", include("tts.urls")),
]
Now a POST to /tts/synthesize/ with a text field will return an MP3 generated by ElevenLabs.
5. Front‑End: Play the Audio in the Browser
Let’s add a tiny HTML page that lets a user type some text, hit “Speak”, and hear the result without a full page reload.
templates/tts/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Voice Demo</title>
<style>
body {font-family: sans-serif; max-width: 600px; margin: 2rem auto;}
textarea {width: 100%; height: 120px;}
</style>
</head>
<body>
<h1>Turn Text into Speech</h1>
<textarea id="txt" placeholder="Enter some text..."></textarea><br>
<button id="speak">Speak</button>
<audio id="player" controls style="margin-top:1rem; width:100%;"></audio>
<script>
const btn = document.getElementById('speak');
const txt = document.getElementById('txt');
const player = document.getElementById('player');
btn.addEventListener('click', async () => {
const form = new FormData();
form.append('text', txt.value);
const resp = await fetch('/tts/synthesize/', {
method: 'POST',
body: form,
});
if (!resp.ok) {
const err = await resp.json();
alert(err.error);
return;
}
const blob = await resp.blob();
const url = URL.createObjectURL(blob);
player.src = url;
player.play();
});
</script>
</body>
</html>
Don’t forget to point Django to the template folder. In settings.py add:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATES[0]["DIRS"] = [os.path.join(BASE_DIR, "templates")]
Create a simple view to render the page:
from django.shortcuts import render
def home(request):
return render(request, "tts/index.html")
Add it to tts/urls.py:
urlpatterns = [
path("", views.home, name="home"),
path("synthesize/", views.synthesize, name="synthesize"),
]
Now run python manage.py runserver, navigate to http://localhost:8000/tts/, type something, and hear it spoken by ElevenLabs’ high‑quality voice.
6. Using Curl (Optional)
If you prefer a quick terminal test, the same endpoint can be hit with curl. First, get a voice ID from ElevenLabs (the dashboard lists them). Then:
curl -X POST -F "text=Hello, Django developers!" \
-F "voice_id=EXAVITQu4vr4xnSDxMaL" \
http://localhost:8000/tts/synthesize/ \
--output speech.mp3
Play speech.mp3 with your favorite media player. The same request works directly against ElevenLabs’ API if you want to bypass Django:
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":"Direct curl call to ElevenLabs!"}' \
--output direct.mp3
7. Voice Cloning (Advanced)
ElevenLabs also lets you upload a few minutes of a speaker’s voice and create a custom voice model. The workflow is:
- Record a clean audio sample (WAV/MP3, 16 kHz+).
- Upload via the dashboard or the
/v1/voices/addendpoint. - Use the returned
voice_idin thegeneratecall above.
Because the SDK abstracts the details, you only need to swap the voice_id string. This opens doors for personalized assistants, brand‑specific narration, or even recreating a character’s voice for a game built on Django.
8. Production Tips
| Concern | Recommendation |
|---|---|
| API quota | Cache generated audio for repeated texts (e.g., blog posts) using Django’s caching framework. |
| Latency | Offload synthesis to a background worker (Celery) and store the MP3 in S3 or your static files. |
| Security | Never expose your ElevenLabs API key to the browser. Keep all calls server‑side. |
| Compliance | If you clone a real person’s voice, make sure you have proper consent and comply with local regulations. |
9. Wrap‑Up
Adding AI‑generated speech to a Django app is surprisingly straightforward when you leverage a dedicated service like ElevenLabs. In just a few lines of Python you can:
- Accept arbitrary text from users.
- Generate lifelike audio on the fly.
- Stream the result back to the browser for instant playback.
All of this can be expanded into richer experiences—audio newsletters, voice‑enabled chatbots, or multilingual narration—without having to train your own TTS model.
Ready to give your Django project a voice?
Grab your free ElevenLabs API key, follow the steps above, and start experimenting. The more you play with different voices and parameters, the more you’ll discover about what’s possible.
Try ElevenLabs now → https://try.elevenlabs.io/kr07zfuqn1bp and let your app speak for itself!
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.