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

How to Add AI Voice to Your Django App

Why Add AI Voice to a Django App? Imagine a learning platform that reads lessons aloud, a customer‑support portal that speaks answers in a friendly tone, or a productivity tool that reads back your to��do list. Voice a

Why Add AI Voice to a Django App?

Imagine a learning platform that reads lessons aloud, a customer‑support portal that speaks answers in a friendly tone, or a productivity tool that reads back your to��do list. Voice adds accessibility, engagement, and a “wow” factor that plain text can’t match. With modern text‑to‑speech (TTS) services you can generate natural‑sounding audio on the fly, and with a few lines of code you can stitch that into a Django project.

In this guide we’ll walk through:

  1. Setting up an ElevenLabs account (the service we’ll use for high‑quality TTS and voice cloning).
  2. Creating a tiny Django app that accepts text, calls the ElevenLabs API, and streams back an MP3.
  3. Adding a front‑end button that plays the generated audio without a page reload.

By the end you’ll have a reusable view you can drop into any Django project and start serving AI‑generated voice instantly.

1. Get an ElevenLabs API Key

ElevenLabs offers one of the most realistic neural TTS engines on the market, plus a voice‑cloning feature if you ever need a custom brand voice. Sign up through their affiliate link so you get a free trial credit:

👉 Get started with ElevenLabs here 👈

Once you’ve confirmed your email, head to Dashboard → API Keys and copy the secret key. Keep it safe – you’ll need it in your Django settings.

2. Install Dependencies

We’ll use the standard Django stack plus requests for the API call. If you’re starting a fresh project:

python -m venv .venv
source .venv/bin/activate
pip install django requests
django-admin startproject voice_demo .
python manage.py startapp tts

Add the new tts app to INSTALLED_APPS in settings.py.

# voice_demo/settings.py
INSTALLED_APPS = [
    # …
    'tts',
]

3. Store the API Key Securely

Never hard‑code secrets. Use Django’s environ or simply an environment variable.

# .env (make sure this file is .gitignore’d)
ELEVENLABS_API_KEY=your_secret_key_here

Load it in settings.py:

import os
from pathlib import Path
import dotenv

BASE_DIR = Path(__file__).resolve().parent.parent
dotenv.load_dotenv(BASE_DIR / ".env")

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

4. Write the TTS View

The core of the integration lives in a single view that:

  1. Receives a POST with the text to speak.
  2. Calls ElevenLabs’ v1/text-to-speech/{voice_id} endpoint.
  3. Returns the MP3 as an HttpResponse with audio/mpeg MIME type.
# tts/views.py
import io
import requests
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

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

# Use one of ElevenLabs’ default voices or a cloned voice ID
DEFAULT_VOICE_ID = "EXAVITQu4vr4xnSDxMaL"  # "Rachel" – feel free to swap

@csrf_exempt
@require_POST
def generate_voice(request):
    data = request.POST
    text = data.get("text", "").strip()
    if not text:
        return JsonResponse({"error": "No text provided"}, status=400)

    url = f"{ELEVENLABS_TTS_URL}/{DEFAULT_VOICE_ID}"
    headers = {
        "xi-api-key": settings.ELEVENLABS_API_KEY,
        "Content-Type": "application/json",
    }
    payload = {
        "text": text,
        "voice_settings": {
            "stability": 0.75,
            "similarity_boost": 0.85,
        },
    }

    # Call ElevenLabs
    response = requests.post(url, json=payload, headers=headers, stream=True)

    if response.status_code != 200:
        return JsonResponse(
            {"error": "ElevenLabs API error", "details": response.text},
            status=response.status_code,
        )

    # Stream the MP3 back to the browser
    audio_bytes = io.BytesIO()
    for chunk in response.iter_content(chunk_size=8192):
        audio_bytes.write(chunk)

    audio_bytes.seek(0)
    return HttpResponse(
        audio_bytes.read(),
        content_type="audio/mpeg",
        headers={"Content-Disposition": 'inline; filename="speech.mp3"'},
    )

URL Configuration

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

urlpatterns = [
    path("speak/", views.generate_voice, name="generate_voice"),
]

Include it in the project’s root URLconf:

# voice_demo/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("tts/", include("tts.urls")),
]

5. Front‑End: Send Text and Play Audio

A minimal HTML page with a textarea, a “Speak” button, and an <audio> element does the trick. We’ll use fetch to POST the text and set the audio source to a Blob URL.

<!-- tts/templates/tts/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AI Voice Demo</title>
  <style>
    body {font-family: Arial, sans-serif; margin: 2rem;}
    textarea {width: 100%; height: 120px;}
    button {margin-top: 1rem; padding: .5rem 1rem;}
  </style>
</head>
<body>
  <h1>Generate AI Voice with ElevenLabs</h1>
  <textarea id="text" placeholder="Enter text to speak..."></textarea><br>
  <button id="speakBtn">Speak</button>
  <audio id="player" controls style="margin-top:1rem; width:100%;"></audio>

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

    btn.addEventListener('click', async () => {
      const txt = textarea.value.trim();
      if (!txt) return alert('Please enter some text');

      btn.disabled = true;
      btn.textContent = 'Generating...';

      try {
        const form = new FormData();
        form.append('text', txt);

        const resp = await fetch('/tts/speak/', {
          method: 'POST',
          body: form,
        });

        if (!resp.ok) {
          const err = await resp.json();
          throw new Error(err.error || 'Unknown error');
        }

        const blob = await resp.blob();
        const url = URL.createObjectURL(blob);
        player.src = url;
        player.play();
      } catch (e) {
        alert('Error: ' + e.message);
      } finally {
        btn.disabled = false;
        btn.textContent = 'Speak';
      }
    });
  </script>
</body>
</html>

Don’t forget to point a simple view to render this template:

# tts/views.py (add at the bottom)
from django.shortcuts import render

def index(request):
    return render(request, "tts/index.html")

And update the URLs:

# tts/urls.py
urlpatterns = [
    path("", views.index, name="index"),
    path("speak/", views.generate_voice, name="generate_voice"),
]

Now run the server:

python manage.py migrate
python manage.py runserver

Navigate to http://127.0.0.1:8000/tts/ and type something like “Welcome to the future of Django apps!” – you should hear a crystal‑clear voice generated by ElevenLabs.

6. Going Further: Voice Cloning & Custom Settings

If you have a brand‑specific voice or want to give users a “record your own voice” experience, ElevenLabs’ cloning API lets you upload a few minutes of audio and obtain a unique voice_id. The request flow is identical; just replace DEFAULT_VOICE_ID with the cloned ID you receive after the upload step.

You can also tweak stability and similarity_boost in the payload to make the voice sound more expressive or more consistent with the original speaker. Experimenting with these values is a fun way to find the perfect tone for your product.

7. Deploying to Production

When you push to production:

  • Store the API key in your environment (Heroku config vars, Docker secrets, etc.).
  • Add a rate‑limit or cache layer (e.g., Django’s cache framework) to avoid hammering the ElevenLabs endpoint for identical requests.
  • Serve the MP3 via a CDN or signed URL if you expect high traffic; the raw view works fine for low‑to‑moderate loads.

8. Recap

Step What you did
Sign up Got an ElevenLabs API key via the affiliate link
Setup Added requests, configured env vars, and created a tts app
Backend Wrote a view that posts text to ElevenLabs and streams back MP3
Frontend Built a tiny UI that posts text via fetch and plays the audio
Next Explored voice cloning, tuning, and production considerations

That’s all you need to start turning any string into a natural‑sounding voice in a Django app.

Ready to give your users a voice?

ElevenLabs makes high‑quality TTS and voice cloning ridiculously easy, and with the code above you can have it up and running in minutes. Give it a spin today – grab your free trial credits through the affiliate link and start building voice‑first experiences:

👉 Try ElevenLabs now! 👈

Happy coding, and enjoy the sound of your own AI��powered app!

📰 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.