DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Voice Cloning Demo App

Introduction

Voice cloning has moved from sci‑fi fantasy to a practical tool you can spin up in an afternoon. Whether you’re building a personalized assistant, adding narration to an e‑learning platform, or just experimenting with AI‑powered speech, a good text‑to‑speech (TTS) service can save you weeks of research. In this post we’ll walk through a complete, end‑to‑end demo app that records a short sample of a user’s voice, sends it to a cloud TTS provider, and then plays back the cloned speech.

The star of the show is ElevenLabs, a service that offers high‑quality voice cloning with a simple REST API. Their free tier is generous enough for a demo, and the affiliate link below gives you instant access to an API key.

👉 Grab your ElevenLabs API key here: https://try.elevenlabs.io/kr07zfuqn1bp

Let’s dive in!

Prerequisites

What you need Why
Python 3.9+ (or Node.js) To run the backend script that talks to ElevenLabs
pip (or npm) Install the HTTP client libraries
A microphone To capture the source voice
A modern browser For the tiny UI that plays back the cloned audio
ElevenLabs API key Authenticates your requests (see next section)

If you’re comfortable with either Python or JavaScript, feel free to pick the language you prefer – the API calls are identical.

Getting an API Key

  1. Visit the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp
  2. Sign up (or log in) and navigate to API → Tokens.
  3. Click Create new token and copy the generated string.

Keep that token secret – treat it like a password.

Setting Up the Project

We’ll create a minimal folder structure:

voice-clone-demo/
├─ backend/
│   ├─ app.py          # Python demo (or server.js for Node)
│   └─ requirements.txt
└─ frontend/
    └─ index.html
Enter fullscreen mode Exit fullscreen mode

Python backend

cd voice-clone-demo/backend
python -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate
pip install requests flask
Enter fullscreen mode Exit fullscreen mode

Add requirements.txt (optional) for reproducibility:

Flask==2.3.2
requests==2.31.0
Enter fullscreen mode Exit fullscreen mode

Node backend (alternative)

cd voice-clone-demo/backend
npm init -y
npm install express axios
Enter fullscreen mode Exit fullscreen mode

Pick the language you like; the rest of the article uses the Python version, but the curl examples work for both.

Making the First Request (curl)

Before we write any code, let’s verify the API works with a simple curl command. Replace YOUR_API_KEY with the token you copied.

curl -X POST "https://api.elevenlabs.io/v1/voice-clone" \
  -H "xi-api-key: YOUR_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F "audio_file=@sample.wav" \
  -F "voice_name=MyClone"
Enter fullscreen mode Exit fullscreen mode

If everything is set up, you’ll receive a JSON payload containing a voice_id. This ID is what you’ll use for subsequent synthesis calls.

Python Example – Upload & Synthesize

Create app.py:

import os
import requests
from flask import Flask, request, jsonify, send_file

app = Flask(__name__)

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

def upload_voice(audio_path, voice_name="DemoClone"):
    url = f"{BASE_URL}/voice-clone"
    headers = {"xi-api-key": ELEVEN_API_KEY}
    files = {"audio_file": open(audio_path, "rb")}
    data = {"voice_name": voice_name}
    resp = requests.post(url, headers=headers, files=files, data=data)
    resp.raise_for_status()
    return resp.json()["voice_id"]

def synthesize(text, voice_id):
    url = f"{BASE_URL}/text-to-speech/{voice_id}"
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "model_id": "eleven_monolingual_v1",
        "voice_settings": {"stability": 0.75, "similarity_boost": 0.85}
    }
    resp = requests.post(url, headers=headers, json=payload)
    resp.raise_for_status()
    # The API returns raw audio bytes
    return resp.content

@app.route("/clone", methods=["POST"])
def clone():
    # Expect a multipart form with a file field called `audio`
    audio = request.files["audio"]
    audio_path = f"/tmp/{audio.filename}"
    audio.save(audio_path)

    voice_id = upload_voice(audio_path)
    return jsonify({"voice_id": voice_id})

@app.route("/speak", methods=["POST"])
def speak():
    data = request.get_json()
    voice_id = data["voice_id"]
    text = data["text"]
    audio_bytes = synthesize(text, voice_id)

    out_path = f"/tmp/output_{voice_id}.mp3"
    with open(out_path, "wb") as f:
        f.write(audio_bytes)

    return send_file(out_path, mimetype="audio/mpeg")

if __name__ == "__main__":
    # Remember to set ELEVEN_API_KEY in your environment
    app.run(debug=True, port=5000)
Enter fullscreen mode Exit fullscreen mode

What this does

  1. /clone – Accepts a short voice sample (≈10 seconds) and creates a clone on ElevenLabs, returning the generated voice_id.
  2. /speak – Takes a voice_id and a text string, calls the ElevenLabs TTS endpoint, and streams back an MP3.

Run it with:

export ELEVEN_API_KEY=YOUR_API_KEY
python app.py
Enter fullscreen mode Exit fullscreen mode

Front‑end – A Tiny HTML UI

Create frontend/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Voice Clone Demo</title>
  <style>
    body {font-family: Arial, sans-serif; margin: 2rem;}
    button, input {margin-top: 1rem;}
  </style>
</head>
<body>
  <h1>Voice Cloning Demo</h1>

  <input type="file" id="audioInput" accept="audio/*" />
  <button id="cloneBtn">Create Clone</button>

  <br/>

  <textarea id="textInput" rows="4" cols="50" placeholder="Enter text to speak..."></textarea>
  <button id="speakBtn" disabled>Speak</button>

  <audio id="player" controls></audio>

  <script>
    const backend = "http://localhost:5000";
    let voiceId = null;

    document.getElementById('cloneBtn').onclick = async () => {
      const file = document.getElementById('audioInput').files[0];
      if (!file) return alert('Select a voice sample first');
      const form = new FormData();
      form.append('audio', file);

      const res = await fetch(`${backend}/clone`, {
        method: 'POST',
        body: form
      });
      const data = await res.json();
      voiceId = data.voice_id;
      document.getElementById('speakBtn').disabled = false;
      alert('Clone created! Voice ID: ' + voiceId);
    };

    document.getElementById('speakBtn').onclick = async () => {
      const text = document.getElementById('textInput').value;
      if (!voiceId) return alert('Clone not ready');
      const res = await fetch(`${backend}/speak`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({voice_id: voiceId, text})
      });
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const player = document.getElementById('player');
      player.src = url;
      player.play();
    };
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Open index.html in your browser, upload a short recording (you can use your phone’s voice memo), click Create Clone, then type any sentence and hit Speak. You should hear the text spoken in your cloned voice!

Testing the Clone

A good sanity check is to compare the original sample with the generated speech. You can use any audio editor (Audacity, VS Code’s audio preview, etc.) to visually inspect waveforms. If the voice sounds off, tweak the stability and similarity_boost parameters in the synthesize function – higher similarity makes the clone sound more like the source, while stability controls prosody smoothness.

Next Steps

  • Persist voice IDs: Store voice_ids in a database so users can reuse their clones across sessions.
  • Add authentication: Guard the /clone and /speak endpoints with JWTs or API keys.
  • Explore other ElevenLabs features: The platform also offers emotion control, multi‑language support, and fine‑grained voice editing.
  • Deploy: Push the Flask app to Render, Fly.io, or any serverless platform, and serve the static front‑end from Netlify or Vercel.

Conclusion

Building a voice cloning demo is surprisingly straightforward when you have a robust API like ElevenLabs behind you. In under an hour we:

  1. Recorded a short voice sample.
  2. Sent it to the ElevenLabs voice‑clone endpoint.
  3. Used the returned voice_id to synthesize arbitrary text.
  4. Served the result through a minimal web UI.

Feel free to experiment with longer texts, different voice settings, or even real‑time streaming (ElevenLabs also offers WebSocket endpoints). The sky’s the limit once you have the cloning engine in place.

🎤 Ready to give it a try? Grab your ElevenLabs API key now and start building voice‑powered experiences: https://try.elevenlabs.io/kr07zfuqn1bp

Happy hacking!

Top comments (0)