Dev.to AI 🤖 Ai 👁 0 📖 6 min read

How to Add AI Voice to Your Django App

Overview Adding a natural‑sounding voice to a Django app opens up a whole new layer of accessibility and user engagement. Whether you want to read out blog posts, provide audio prompts for a chatbot, or build a voice‑d

Overview

Adding a natural‑sounding voice to a Django app opens up a whole new layer of accessibility and user engagement. Whether you want to read out blog posts, provide audio prompts for a chatbot, or build a voice‑driven tutorial, the core pieces are the same:

  1. Text‑to‑Speech (TTS) service – turns a string into an audio file.
  2. Backend endpoint – receives the text, calls the TTS API, and returns the audio URL or binary.
  3. Frontend player – fetches the audio and plays it in the browser.

In this post we’ll wire up ElevenLabs – a high‑quality, developer‑friendly TTS platform – to a Django project, expose a tiny REST endpoint, and hook it up to a vanilla JavaScript player. By the end you’ll have a reusable speak/ view you can call from anywhere in your app.

Why ElevenLabs?

Their API is straightforward, the voices sound remarkably human, and they even support voice cloning if you ever need a custom brand voice. You can sign up through this affiliate link and get a free trial: ElevenLabs.

Prerequisites

What you need Why
Python 3.9+ Django 4.x runs best on recent Python.
Django 4.x The example uses class‑based views and path() routing.
ElevenLabs API key You’ll need it to authenticate requests.
Node (optional) If you prefer a React front‑end, the same endpoint works.
cURL Handy for quick testing from the terminal.

Create a fresh virtual environment and install Django:

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 tts to INSTALLED_APPS in settings.py.

Setting Up the ElevenLabs API

ElevenLabs exposes a simple REST endpoint:

POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}
Headers:
  xi-api-key: <YOUR_API_KEY>
  Content-Type: application/json
Body:
{
  "text": "Hello world",
  "model_id": "eleven_multilingual_v2",
  "voice_settings": { "stability": 0.5, "similarity_boost": 0.75 }
}

Grab your API key from the ElevenLabs dashboard and pick a default voice_id (e.g., EXAVITQu4vr4xnSDxMaL). Keep the key out of source control – store it in Django’s settings.py or use django-environ.

# voice_demo/settings.py
ELEVENLABS_API_KEY = os.getenv('ELEVENLABS_API_KEY')
ELEVENLABS_DEFAULT_VOICE = 'EXAVITQu4vr4xnSDxMaL'   # change to any voice you like

Django Backend Integration

1. Create a serializer‑like helper

We’ll keep the view thin and delegate the HTTP call to a small utility function.

# tts/utils.py
import requests
from django.conf import settings

ELEVEN_API_URL = "https://api.elevenlabs.io/v1/text-to-speech"

def synthesize_text(text: str, voice_id: str = None) -> bytes:
    voice_id = voice_id or settings.ELEVENLABS_DEFAULT_VOICE
    url = f"{ELEVEN_API_URL}/{voice_id}"
    headers = {
        "xi-api-key": settings.ELEVENLABS_API_KEY,
        "Content-Type": "application/json",
    }
    payload = {
        "text": text,
        "model_id": "eleven_multilingual_v2",
        "voice_settings": {"stability": 0.5, "similarity_boost": 0.75},
    }

    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    return response.content   # binary MP3 data

2. Expose a view

We’ll accept JSON { "text": "...", "voice_id": "optional" } and return the MP3 as audio/mpeg.

# tts/views.py
import base64
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse
from django.views import View
from .utils import synthesize_text

class SpeakView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            text = data["text"]
            voice_id = data.get("voice_id")
        except (KeyError, json.JSONDecodeError):
            return HttpResponseBadRequest("Invalid JSON payload")

        try:
            audio_bytes = synthesize_text(text, voice_id)
        except Exception as e:
            return HttpResponseBadRequest(f"TTS error: {e}")

        # Option 1: stream raw MP3
        # return HttpResponse(audio_bytes, content_type="audio/mpeg")

        # Option 2: embed as base64 (handy for quick JS demos)
        b64 = base64.b64encode(audio_bytes).decode()
        return JsonResponse({"audio_base64": b64})

Add the route:

# voice_demo/urls.py
from django.urls import path
from tts.views import SpeakView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/speak/', SpeakView.as_view(), name='speak'),
]

Tip: If you prefer streaming the MP3 directly, uncomment the Option 1 line and adjust the front‑end accordingly.

3. Test with cURL

curl -X POST http://127.0.0.1:8000/api/speak/ \
  -H "Content-Type: application/json" \
  -d '{"text":"Welcome to your Django app!"}'

You should receive a JSON response with an audio_base64 field. Decode it locally to verify the voice.

Frontend Playback

A minimal HTML page with vanilla JavaScript can consume the endpoint and play the sound instantly.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Django TTS Demo</title>
</head>
<body>
  <h1>Text‑to‑Speech Demo</h1>
  <textarea id="txt" rows="4" cols="50">Hello, Django world!</textarea><br>
  <button id="speakBtn">Speak</button>
  <audio id="player" controls></audio>

  <script>
    const btn = document.getElementById('speakBtn');
    const txt = document.getElementById('txt');
    const player = document.getElementById('player');

    btn.addEventListener('click', async () => {
      const resp = await fetch('/api/speak/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: txt.value })
      });
      const data = await resp.json();
      player.src = `data:audio/mpeg;base64,${data.audio_base64}`;
      player.play();
    });
  </script>
</body>
</html>

Place this file in templates/tts_demo.html and render it via a simple view, or serve it as a static page. The key line is the data: URI ��� it lets us play the returned base64 MP3 without storing a temporary file on disk.

Optional: Voice Cloning

ElevenLabs also offers voice cloning: upload a short (≈30 s) sample of a speaker and receive a new voice_id you can reuse. The flow is:

  1. POST the audio file to /v1/voices/add (requires the same API key).
  2. Poll /v1/voices/{voice_id} until the status becomes ready.
  3. Use the new voice_id in the synthesize_text call.

Because cloning is a separate product tier, you might want to expose a separate admin endpoint that stores the custom voice_id in your Django model. The rest of the pipeline stays identical.

Testing in CI

For automated tests you don’t want to hit the real ElevenLabs service every run. Mock the requests.post call with responses or unittest.mock:

from unittest.mock import patch
from django.test import TestCase
from tts.views import SpeakView

class SpeakViewTest(TestCase):
    @patch('tts.utils.requests.post')
    def test_speak_returns_base64(self, mock_post):
        mock_post.return_value.status_code = 200
        mock_post.return_value.content = b'FAKEAUDIO'
        resp = self.client.post('/api/speak/', {'text': 'test'}, content_type='application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertIn('audio_base64', resp.json())

This keeps your CI fast and deterministic.

Wrap‑up

You now have a plug‑and‑play TTS endpoint that leverages ElevenLabs’ state‑of‑the‑art voices. The pattern scales nicely:

  • Swap the default voice in settings.py to change the brand tone.
  • Add a cache (e.g., Django’s cache framework) to avoid re‑synthesizing the same text repeatedly.
  • Combine with Django Channels for real‑time streaming in chat applications.

The only moving part is the API key – keep it secret, rotate it occasionally, and you’ll have a reliable voice layer for months to come.

Ready to give your users a voice?

Head over to ElevenLabs, grab your API key, and start experimenting with the code above. The affiliate link below gives you a quick start and a few free minutes of audio generation:

Try ElevenLabs now →

Happy coding, and may your apps speak as fluently as you type!

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.