DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Voice-Powered Accessibility Tool

The Problem: Accessibility Needs a Voice Layer

Every day, developers build amazing web and mobile experiences, but a large portion of users still struggle to interact with those experiences using traditional UI elements. Whether it’s the elderly, people with visual impairments, or anyone dealing with temporary injuries, a reliable voice‑powered layer can transform an app from nice to have into a truly inclusive product.

Voice AI brings two core capabilities to the table:

  1. Text‑to‑Speech (TTS) – turning any piece of text into natural, expressive speech.
  2. Voice Cloning – creating a personalized voice model that can speak in a user’s own voice or a brand‑specific voice.

When these two pieces are combined, you can build a tool that reads aloud web pages, PDFs, or even user‑generated content, while letting the user choose a voice that feels most natural to them.


Why ElevenLabs?

ElevenLabs provides an industry‑leading TTS API that is:

  • High‑quality: 90 %+ intelligibility and natural prosody.
  • Fast: Real‑time streaming support for live applications.
  • Flexible: Supports voice cloning via short audio samples.

For developers who want to prototype quickly and then ship a production‑ready product, ElevenLabs offers a simple REST API, SDKs, and generous free tiers. If you’re ready to power your accessibility tool with a voice engine that actually sounds human, ElevenLabs is the place to start: https://try.elevenlabs.io/kr07zfuqn1bp.


Architecture Overview

Below is a minimal architecture that covers the most common use‑cases:

┌───────────────┐          ┌───────────────────┐
│  Frontend UI  │ <------> │  Backend Service   │
└───────▲───────┘          └───────┬─────▲───────┘
        │                           │     │
        │ fetch text                │     │
        │                           │     │
        │  ┌─────────────────────┐  │     │
        │  │  TTS Engine (Eleven) │  │     │
        │  └─────────────────────┘  │     │
        │                           │     │
        ▼                           ▼     ▼
   Web page / PDF                 Audio Stream
Enter fullscreen mode Exit fullscreen mode
  1. Frontend – Accepts user input (URL, PDF upload, or text) and displays the spoken output in the browser or a mobile app.
  2. Backend – Handles heavy lifting: fetching content, invoking ElevenLabs API, and streaming audio back to the client.
  3. ElevenLabs – Provides the voice synthesis and cloning services.

Let’s dive into the code.


1. Setting Up

a. Get an API Key

Sign up at https://try.elevenlabs.io/kr07zfuqn1bp and retrieve your API key. Keep it secret; it will be used in server‑side code.

b. Install Dependencies

We’ll use a lightweight Python stack: Flask for the web server and requests for HTTP calls.

pip install flask requests
Enter fullscreen mode Exit fullscreen mode

2. TTS Endpoint

Create a file called app.py:

import os
import json
import requests
from flask import Flask, request, Response

app = Flask(__name__)
ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")  # Set this in your environment
ELEVEN_TTS_URL = "https://api.elevenlabs.io/v1/text-to-speech"

# Helper: Stream audio from ElevenLabs
def stream_tts(text, voice_id="en-US-Standard-B"):
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    data = {
        "text": text,
        "voice_settings": {
            "stability": 0.5,
            "similarity_boost": 0.5
        }
    }

    # Streaming endpoint: returns raw audio bytes
    resp = requests.post(
        f"{ELEVEN_TTS_URL}/{voice_id}",
        headers=headers,
        json=data,
        stream=True,
    )
    resp.raise_for_status()
    return resp.iter_content(chunk_size=4096)

@app.route("/speak", methods=["POST"])
def speak():
    payload = request.get_json()
    text = payload.get("text", "")
    voice_id = payload.get("voice_id", "en-US-Standard-B")

    audio_iter = stream_tts(text, voice_id)

    # Flask streaming response
    return Response(
        audio_iter,
        mimetype="audio/mpeg",
        headers={"Content-Disposition": "attachment; filename=output.mp3"}
    )

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

How it works

  • The /speak endpoint accepts a JSON body: { "text": "...", "voice_id": "..." }.
  • It calls ElevenLabs’ streaming TTS endpoint and pipes the audio back to the client without buffering the entire file in memory.

3. Voice Cloning Demo

ElevenLabs lets you create a custom voice model from a short audio sample. The workflow is:

  1. Upload an audio clip (≈ 30 seconds).
  2. Wait for the model to train (you’ll get a model_id).
  3. Use that model_id in subsequent TTS calls.

Below is a quick script that creates a voice clone and then uses it:

import os
import time
import json
import requests

ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"

def create_voice_clone(audio_path, name="MyClone"):
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    files = {"file": open(audio_path, "rb")}
    data = {"name": name}

    resp = requests.post(
        f"{BASE_URL}/voice-cloning/create",
        headers=headers,
        files=files,
        data=data
    )
    resp.raise_for_status()
    model_id = resp.json()["model_id"]
    print(f"Created model: {model_id}")
    return model_id

def synthesize_with_clone(text, model_id):
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    data = {
        "text": text,
        "model_id": model_id
    }

    resp = requests.post(
        f"{BASE_URL}/text-to-speech/{model_id}",
        headers=headers,
        json=data,
        stream=True
    )
    resp.raise_for_status()
    with open("clone_output.mp3", "wb") as f:
        for chunk in resp.iter_content(chunk_size=4096):
            f.write(chunk)
    print("Saved clone audio to clone_output.mp3")

# Example usage
if __name__ == "__main__":
    model_id = create_voice_clone("sample.wav")
    # Wait a bit for the model to train
    time.sleep(5)
    synthesize_with_clone("Hello, this is a cloned voice.", model_id)
Enter fullscreen mode Exit fullscreen mode

Tip: The cloning endpoint is still in beta, so expect longer processing times for large models. For production, cache the model_id and reuse it.


4. Frontend Integration

If you’re building a web app, the easiest way to play back the audio is to use the <audio> element and fetch the /speak endpoint.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Voice Accessibility Demo</title>
</head>
<body>
<textarea id="text" rows="6" cols="60">Type something here...</textarea><br>
<button id="speakBtn">Speak</button>
<audio id="audioPlayer" controls></audio>

<script>
document.getElementById('speakBtn').onclick = async () => {
  const text = document.getElementById('text').value;
  const res = await fetch('/speak', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text })
  });

  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const audio = document.getElementById('audioPlayer');
  audio.src = url;
};
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Pro tip: Use fetch with signal to cancel a request if the user types again before the audio finishes. This keeps the UI responsive.


5. Going Live: Deploying the Service

  1. Dockerize your Flask app for consistency across environments.
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV ELEVEN_API_KEY=${ELEVEN_API_KEY}
EXPOSE 5000
CMD ["python", "app.py"]
Enter fullscreen mode Exit fullscreen mode
  1. CI/CD – Push to GitHub, use GitHub Actions to build and push the Docker image to Docker Hub or GitHub Packages.

  2. Hosting – Deploy to Render, Fly.io, or any platform that supports Docker containers.

  3. SSL – Use a reverse proxy (NGINX or Cloudflare) to serve over HTTPS. ElevenLabs requires HTTPS for certain endpoints.


6. Accessibility Checklist

Feature Why it matters Implementation hint
Live captions Helps users verify the spoken content Use Web Speech API or a custom captioning service
Custom voice selection Allows users to choose a voice they’re comfortable with Store voice preferences in a database
Keyboard navigation Makes the UI operable without a mouse Ensure all controls are focusable and have aria‑labels
Color contrast Ensures visual clarity for low‑vision users Use WCAG AA color palettes
Error handling Provides feedback when TTS fails Show toast notifications or fallback text

7. Next‑Level Features

  • Real‑time translation – Combine ElevenLabs with a translation API to speak content in the user’s native language.
  • Speech‑to‑Text – Add a microphone input that records, transcribes, and then re‑speaks the user’s speech.
  • Personalization – Store user‑specific voice models and apply them automatically when the user logs in.
  • Analytics – Track which pages are read most often to prioritize improvements.

Wrap‑Up

Building a voice‑powered accessibility tool is more than adding a “read aloud” button. It’s about providing a natural, flexible, and personalized experience that respects every user’s needs. With ElevenLabs’ high‑fidelity TTS and powerful cloning capabilities, you can prototype a robust solution in just a few hours.

Ready to give your app a voice? Grab your API key from https://try.elevenlabs.io/kr07zfuqn1bp, follow the snippets above, and start building today. Happy coding!

Top comments (0)