DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Create an AI Dubbing Tool for Video Content

Why AI Dubbing Matters

If you’ve ever tried to repurpose a YouTube video for a new market, you know the pain of hiring voice actors, dealing with contracts, and then syncing the new audio back to the footage. Modern text‑to‑speech (TTS) engines have closed the quality gap dramatically, making it possible to generate natural‑sounding narration in seconds. By coupling a TTS service with a little scripting, you can build a fully automated dubbing pipeline that works for any length of video.

In this guide we’ll walk through a simple, production‑ready workflow that:

  1. Extracts the spoken transcript from a video (or uses an existing script).
  2. Sends the text to a high‑quality TTS API (ElevenLabs).
  3. Aligns the generated audio with the original video using FFmpeg.

By the end you’ll have a Python script that can turn a 10‑minute tutorial into a dubbed version in another language or with a different voice—no studio required.


Prerequisites

Item Reason
Python 3.9+ Core scripting language
FFmpeg Audio/video muxing and time‑stretching
ElevenLabs API key High‑fidelity neural TTS (sign‑up at the link below)
A source video Anything MP4, MOV, etc.
(Optional) Whisper or Google Speech‑to‑Text To generate a transcript automatically

You can install the Python dependencies with:

pip install requests tqdm pydub
Enter fullscreen mode Exit fullscreen mode

Make sure ffmpeg is on your PATH. On macOS you can use brew install ffmpeg; on Ubuntu sudo apt-get install ffmpeg.


Grab a Transcript

If you already have a script, skip this step. Otherwise, you can use OpenAI’s Whisper to generate one:

import subprocess, json, pathlib

def whisper_transcribe(video_path: str) -> str:
    # Whisper CLI expects an audio file; extract a short wav first
    wav_path = pathlib.Path("temp.wav")
    subprocess.run([
        "ffmpeg", "-y", "-i", video_path,
        "-vn", "-ac", "1", "-ar", "16000", str(wav_path)
    ], check=True)

    # Run Whisper (install via pip install -U openai-whisper)
    import whisper
    model = whisper.load_model("base")
    result = model.transcribe(str(wav_path))
    wav_path.unlink()  # clean up
    return result["text"]
Enter fullscreen mode Exit fullscreen mode

The function returns a plain‑text transcript you can edit before sending it to the TTS engine.


Generate Speech with ElevenLabs

ElevenLabs offers one of the most natural‑sounding neural TTS services today. Sign up at the ElevenLabs affiliate link to get a free API key.

Here’s a minimal Python wrapper that streams the audio back as an MP3 file:

import requests, pathlib, json

ELEVEN_API_KEY = "YOUR_ELEVENLABS_API_KEY"
VOICE_ID = "21m00Tcm4TlvDq8ikWAM"   # default "Rachel" voice; replace with any you like

def synthesize(text: str, out_path: pathlib.Path):
    url = f"https://api.elevenlabs.io/v1/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
        }
    }

    response = requests.post(url, headers=headers, json=payload, stream=True)
    response.raise_for_status()

    with open(out_path, "wb") as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

# Example usage:
synth_path = pathlib.Path("dubbed.mp3")
synthesize("Hello, world! This is an AI‑generated dub.", synth_path)
Enter fullscreen mode Exit fullscreen mode

Tip: You can clone a custom voice by uploading a few minutes of your own recordings to ElevenLabs. The API then returns a new voice_id you can use in the same request.


Align Audio to the Original Video

The raw TTS audio will be the same length as the input text, which rarely matches the original timing. A quick way to keep the video’s pacing is to use FFmpeg’s -filter_complex with atempo to stretch or shrink the audio.

#!/usr/bin/env bash
# arguments: $1 = original video, $2 = generated audio, $3 = output video
set -e

VIDEO=$1
AUDIO=$2
OUT=$3

# Get durations (seconds)
VID_DUR=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$VIDEO")
AUD_DUR=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$AUDIO")

# Compute speed factor (video / audio)
SPEED=$(python -c "print($VID_DUR / $AUD_DUR)")

ffmpeg -y -i "$VIDEO" -i "$AUDIO" \
  -filter_complex "[1:a]atempo=$SPEED[a]" \
  -map 0:v -map "[a]" -c:v copy -c:a aac -b:a 192k "$OUT"
Enter fullscreen mode Exit fullscreen mode

The script reads the durations, calculates the required tempo change, and re‑encodes the audio while keeping the video stream untouched. For more precise lip‑sync you could use a forced‑alignment library (e.g., aeneas), but the tempo trick works well for narration and slide‑based videos.


Full End‑to‑End Example (Python)

Putting it all together, here’s a concise script that:

  1. Extracts a transcript (or reads a supplied .txt).
  2. Calls ElevenLabs to synthesize the voice.
  3. Adjusts the audio tempo to match the source video.
import pathlib, subprocess, json, sys
from tqdm import tqdm

# ---- Config -------------------------------------------------
ELEVEN_API_KEY = "YOUR_ELEVENLABS_API_KEY"
VOICE_ID = "21m00Tcm4TlvDq8ikWAM"
# -----------------------------------------------------------

def run_cmd(cmd):
    subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def get_duration(file_path: pathlib.Path) -> float:
    result = subprocess.check_output([
        "ffprobe", "-v", "error",
        "-show_entries", "format=duration",
        "-of", "default=noprint_wrappers=1:nokey=1",
        str(file_path)
    ])
    return float(result)

def main(video_path: str, transcript_path: str = None):
    video = pathlib.Path(video_path)
    if not transcript_path:
        # Auto‑generate transcript with Whisper
        print("Generating transcript with Whisper…")
        transcript = whisper_transcribe(str(video))
    else:
        transcript = pathlib.Path(transcript_path).read_text(encoding="utf-8")

    # Step 1 – Synthesize
    audio_file = pathlib.Path("dubbed.mp3")
    print("Calling ElevenLabs TTS…")
    synthesize(transcript, audio_file)

    # Step 2 – Tempo match
    vid_dur = get_duration(video)
    aud_dur = get_duration(audio_file)
    speed = vid_dur / aud_dur
    print(f"Video length: {vid_dur:.2f}s, Audio length: {aud_dur:.2f}s, Speed factor: {speed:.3f}")

    output = pathlib.Path("dubbed_output.mp4")
    run_cmd([
        "ffmpeg", "-y",
        "-i", str(video),
        "-i", str(audio_file),
        "-filter_complex", f"[1:a]atempo={speed}[a]",
        "-map", "0:v", "-map", "[a]",
        "-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
        str(output)
    ])
    print(f"✅ Dubbing complete → {output}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python dub.py <video_path> [transcript.txt]")
        sys.exit(1)
    main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
Enter fullscreen mode Exit fullscreen mode

Run it like:

python dub.py my_tutorial.mp4
Enter fullscreen mode Exit fullscreen mode

You’ll end up with dubbed_output.mp4 that contains the AI‑generated narration perfectly timed to the original visuals.


Going Further

  • Multi‑language dubbing – Translate the transcript with DeepL or Google Translate before feeding it to ElevenLabs.
  • Custom voice cloning – Upload a few minutes of a brand’s voice to ElevenLabs, then use the returned voice_id for consistent branding.
  • Batch processing – Wrap the script in a for loop or a simple Celery worker to process an entire playlist.
  • Subtitle generation – Export the transcript to .srt and embed it using FFmpeg’s -c:s mov_text for a fully localized package.

Wrap‑up

Building an AI dubbing tool is now a weekend project rather than a months‑long R&D effort. By leveraging ElevenLabs’ state‑of‑the‑art TTS API, a bit of Python, and the ubiquitous FFmpeg utility, you can automate the entire pipeline from raw video to a polished dubbed version.

Ready to give it a spin? Grab your ElevenLabs API key via the affiliate link, plug it into the script, and start generating professional‑grade voiceovers in seconds. Happy dubbing!

Top comments (0)