> This page is for Model APIs.

> For clean Markdown of any page, append `.md` to the page URL.
> For a complete documentation index, see https://docs.sarvam.ai/llms.txt. For a section index, append `/llms.txt` to any section URL (for example https://docs.sarvam.ai/voice-agents/llms.txt).
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.sarvam.ai/_mcp/server.

# Realtime Speech Dubbing

> Build a Gradio app that dubs live speech into another Indian language in the speaker's own voice, using Saaras v4 streaming speech-to-text, Gemma 4 translation, and Instant Voice Cloning.

## **Overview**

This cookbook builds a live dubbing app. You speak into the microphone in one language, and each time you pause, the app plays that sentence back in another language, in your own voice. You can keep talking while earlier sentences are still being translated and played.

It chains three Sarvam APIs:

| Stage     | API                                                                                         | What it does                                                                       |
| --------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Listen    | [Saaras v4 Realtime Streaming](/api/api-guides-tutorials/speech-to-text/realtime-streaming) | Transcribes the microphone stream and detects when you stop speaking               |
| Translate | [Gemma 4](/api/token-factory/models/gemma-4-31b) on Token Factory                           | Translates each finished sentence, using the previous three as context             |
| Speak     | [Instant Voice Cloning](/api/api-guides-tutorials/voice-cloning/overview)                   | Speaks the translation in a voice cloned from your own speech, or in a saved voice |

**What you'll build:**

* A Gradio app that streams your browser microphone for as long as you keep recording
* Sentence-by-sentence dubbing, played back in the order you spoke
* A choice between cloning your voice from each sentence or reusing a saved workspace voice
* One combined WAV of the whole dubbed session when you press Stop

#### [View on GitHub](https://github.com/sarvamai/sarvam-ai-cookbook/tree/main/examples/Realtime_Speech_Dubbing)

Browse the full source for this app in the sarvam-ai-cookbook repo.

#### [Run Code Locally](#2-clone-and-install)

Jump to Clone and Install to set this demo up on your machine.

### Business Value

* Live interpretation for a talk, demo, or stage session without a human interpreter
* The speaker keeps their own voice in the dubbed language
* A dubbed recording of the full session, ready to share afterwards

#### Events

Dub a live talk into another language and play each finished sentence without waiting for the whole recording.

#### Product demos

Narrate a walkthrough in one language and let the audience hear it in another, in the same voice.

#### Accessibility

Offer a spoken translation alongside the original speaker for listeners who need another language.

## **How It Works**

#### Stream the microphone to Saaras v4

Gradio sends microphone audio to the app every 250 ms, and the app forwards it to Saaras v4 over a WebSocket. Saaras detects the end of each sentence with server-side voice activity detection (VAD) once you pause for the configured silence duration.

#### Translate the finished sentence

Gemma 4 translates the sentence into the target language. The last three source and translation pairs are sent as context, so names and terminology stay consistent.

#### Clone the voice and play

Instant Voice Cloning speaks the translation as an MP3. By default, the app uses the audio of that same sentence as the voice reference, so the dub sounds like the speaker. Sentences play strictly in the order they were spoken.

#### Export on Stop

Stop cancels unfinished work and writes one combined WAV of every completed sentence, including sentences that had not played yet.

Each dubbed sentence plays a few seconds after you pause. In our tests, a sentence played about 2 to 3 seconds after the pause when cloning from the speaker's own audio, and under 2 seconds with a saved voice. Most of that time is voice synthesis.

## **1. Prerequisites**

* Python 3.10 or higher
* [FFmpeg](https://ffmpeg.org/download.html) on your `PATH`, used to decode the dubbed MP3s (`brew install ffmpeg`, `sudo apt install ffmpeg`, or `winget install ffmpeg`)
* A Sarvam API key, sign up on the [Sarvam AI Dashboard](https://indus.sarvam.ai/key-management?ref=docs) to get one
* A browser with microphone access, and headphones

## **2. Clone and Install**

#### macOS/Linux

```bash
git clone https://github.com/sarvamai/sarvam-ai-cookbook.git
cd sarvam-ai-cookbook/examples/Realtime_Speech_Dubbing
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

#### Windows

```powershell
git clone https://github.com/sarvamai/sarvam-ai-cookbook.git
cd sarvam-ai-cookbook/examples/Realtime_Speech_Dubbing
py -3 -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
```

## **3. Configure Environment Variables**

Copy the example file and add your key:

#### macOS/Linux

```bash
cp .env.example .env
```

#### Windows

```powershell
copy .env.example .env
```

```env
SARVAM_API_KEY=sk_xxxxxxxxxxxxxxxxxxxxxxxx
```

You can export `SARVAM_API_KEY` in your shell instead. The key is only read on the server; it never reaches the browser.

## **4. Run It**

```bash
python app.py
```

Open the local URL Gradio prints, usually [http://127.0.0.1:7860](http://127.0.0.1:7860).

> **Warning**
>
> If Gradio also prints a public `gradio.live` link, anyone who opens it can use the app, and every request is billed to your API key. Don't share that link. To turn it off, change `launch(share=True)` to `launch(share=False)` at the bottom of `app.py`.

## **5. Use the App**

#### Pick languages

Choose a **Source language** (default `Auto detect`) and a **Target language** (default `English`).

#### Optional: adjust Advanced options

Pick a saved voice, or change pause and reference settings. See [Available Options](#available-options).

#### Record

Put on headphones, click **Record** on the microphone, and allow microphone access.

#### Speak and pause

Speak a sentence, then pause. The dubbed sentence plays in the **Dubbed audio** player. The **Stage**, transcript, translation, segment history, and queue depth update as you go.

#### Stop

Click **Stop** to end the session. The **Combined WAV** player shows the full dubbed recording.

> **Note**
>
> Language and Advanced options are locked while recording. Press Stop before changing them.

## **6. Pipeline Walkthrough**

### Step 1: Open a Saaras v4 realtime stream

`sarvam_streams.py` opens one WebSocket per session in server VAD mode. `silence_duration_ms` comes from the **Pause duration** setting, and `return_timestamps` adds `start_s`/`end_s` to each final transcript, so the app can cut the matching audio out of the recording to use as a voice reference:

```python
self._socket = await self._exit_stack.enter_async_context(
    self._client.speech_to_text_realtime_streaming.connect(
        language_code=to_saaras_language(self._source_language),
        model="saaras:v4",
        endpointing="vad",
        silence_duration_ms=str(int(round(self._pause_seconds * 1000))),
        return_timestamps="true",
        encoding="linear16",
        sample_rate="16000",
    )
)
```

Browser audio arrives at 44.1 or 48 kHz. `audio.py` downmixes it to mono and resamples it to 16 kHz 16-bit PCM before sending, because the realtime endpoint accepts only 8 or 16 kHz.

### Step 2: Translate with context

`translation.py` sends a system prompt, the last three successful source and translation pairs, and the new sentence to Gemma 4 through Chat Completions V2:

```python
response = await asyncio.wait_for(
    self.client.chat.completions_v2(
        messages=messages,  # system prompt + last 3 pairs + new sentence
        model="gemma4",
        stream=False,
    ),
    timeout=self.timeout_seconds,
)
```

Timeouts, network errors, and `408`/`429`/`5xx` responses are retried up to three times with backoff. Other errors fail that sentence only; the session keeps running.

### Step 3: Clone the voice

`sarvam_streams.py` calls Instant Voice Cloning with exactly one voice source: the sentence's own audio as `ref_audio`, or a saved `voice_id`:

```python
kwargs = {
    "text": text,
    "language_code": self._target_language,
    "output_audio_codec": "mp3",
    "enable_vad": True,
}
if self.voice_id is not None:
    kwargs["voice_id"] = self.voice_id
else:
    kwargs["remove_background_noise"] = self._remove_background_noise
    kwargs["ref_audio"] = reference_wav

response = await self._client.voice_cloning.convert(**kwargs)
```

Before the call, the reference audio is trimmed to **Max chunk duration**, and empty, silent, or shorter than 0.25 second clips are rejected without calling the API.

### Step 4: Play in order and export

`interpreter.py` queues sentences by their Saaras utterance index, so a slow sentence never plays after a later one. `playback.py` releases the next MP3 only after the current one has finished playing. On Stop, every completed MP3 is decoded with FFmpeg and placed on one timeline that follows the original speech timing without overlapping, then written as a single WAV.

## **Available Options**

### Advanced options

| Option                      | Default           | What it does                                                                                                                                                                                                                                           |
| --------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Saved voice ID**          | `None`            | `None` clones the voice from each sentence's own audio. Pick a saved voice to reuse it for every sentence; synthesis is faster because no reference audio is uploaded. Saved voices come from [List Voices](/api-reference/voice-cloning/list-voices). |
| **Pause duration**          | `1.5` s           | Silence that ends a sentence, sent to Saaras as `silence_duration_ms`. Lower it for faster turnaround; raise it if sentences get split mid-thought.                                                                                                    |
| **Max chunk duration**      | `12` s (max `15`) | Longest voice reference sent for cloning. Only shown when Saved voice ID is `None`. The API accepts up to 15 seconds, and 10 to 15 seconds gives the best clone.                                                                                       |
| **Remove background noise** | On                | Cleans the reference before cloning. Turning it off saves about a second per sentence but can lower clone quality in noisy rooms. Not used with a saved voice.                                                                                         |

### Supported Languages

**Source language:** `Auto detect` or any of the 23 languages Saaras v4 supports. See [Realtime Streaming language support](/api/api-guides-tutorials/speech-to-text/realtime-streaming#language-support).

**Target language:** the 12 languages Instant Voice Cloning supports:

| Language | Code    | Language  | Code    |
| -------- | ------- | --------- | ------- |
| Assamese | `as-IN` | Malayalam | `ml-IN` |
| Bengali  | `bn-IN` | Marathi   | `mr-IN` |
| English  | `en-IN` | Odia      | `od-IN` |
| Gujarati | `gu-IN` | Punjabi   | `pa-IN` |
| Hindi    | `hi-IN` | Tamil     | `ta-IN` |
| Kannada  | `kn-IN` | Telugu    | `te-IN` |

> **Note**
>
> Odia uses two different codes: Saaras v4 realtime expects `or-IN` and voice cloning expects `od-IN`. The app converts between them, so pick **Odia** in either dropdown.

> **Note**
>
> Gemma 4 is a general model and is not specifically tuned for Indian languages. Check translation quality for your target language before using this for a live audience.

## **Output Files**

Everything is written to `outputs/` in the example directory:

| File                | Contents                                                                                                                                                                                  |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `combined-<id>.wav` | The full dubbed session, written on Stop. Mono, 16 kHz.                                                                                                                                   |
| `playback-<id>.mp3` | One file per dubbed sentence, served to the player. These are not deleted automatically.                                                                                                  |
| `timings.jsonl`     | One line per completed sentence with stage timestamps and `saaras_finalize_ms`, `pipeline_trigger_ms`, `translation_ms`, and `tts_ms`. It contains no transcript text, audio, or API key. |

Use `timings.jsonl` to see which stage is slow on your network.

## **Tips & Best Practices**

* **Use headphones**: Without them, the microphone picks up the dubbed playback and transcribes it as new speech. Keep browser echo cancellation on as well.
* **Set the source language when you know it**: `Auto detect` works, but a fixed source language gives more consistent transcripts.
* **Use a saved voice for long sessions**: It skips uploading reference audio and background-noise removal for every sentence, which roughly halves synthesis time.
* **Speak in complete sentences**: Each pause becomes one translation. Fragments translate worse than full sentences.
* **Keep it local**: This demo is built for one speaker in one browser session. Don't expose it publicly with your API key.

## **Troubleshooting**

* **`SARVAM_API_KEY is not set`**: Add the key to `.env` in the example directory, or export it in your shell, then restart the app.
* **Only `None` in the Saved voice ID list**: Your workspace has no saved voices, or the voice list could not load. Create one with [Create Voice](/api-reference/voice-cloning).
* **The microphone doesn't start**: Allow microphone access for the page. Browsers only allow the microphone on `localhost`, `127.0.0.1`, or HTTPS, so don't open the app by LAN IP.
* **A transcript appears but no audio plays**: Check the **Segment history** table for an error on that sentence. A failed sentence is skipped; later sentences still play.
* **The app hears its own output**: Use headphones and lower the speaker volume.
* **Queue depth keeps growing**: Translation and synthesis are slower than your speech on this connection. Pause longer between sentences, switch to a saved voice, or stop and retry on a faster network.
* **`Could not decode MP3 audio`**: FFmpeg is missing from `PATH`. Install it and restart the app.

## **Error Handling**

You may encounter these errors while using the underlying APIs:

* **403 Forbidden** (`invalid_api_key_error`), invalid API key. Use a valid key from the [Sarvam AI Dashboard](https://indus.sarvam.ai/key-management?ref=docs).
* **429 Too Many Requests** (`rate_limit_exceeded_error`), too many requests. The app retries translation automatically; check [Credits & Rate Limits](/api/getting-started/pricing#rate-limits) if it persists.
* **WebSocket close `4000`**, invalid model, language, or other connection parameter, or your account is not enabled for realtime streaming.
* **WebSocket close `1008`**, no audio received for 60 seconds. The app sends a keepalive ping every 30 seconds to avoid this.
* **400 Bad Request** on voice cloning, usually a reference clip over 15 seconds or 10 MB, or an unsupported target language.

For the full error-code table and SDK exception reference, see [Errors & Troubleshooting](/api/getting-started/errors-troubleshooting).

## **Additional Resources**

* **Documentation**: [docs.sarvam.ai](https://docs.sarvam.ai)
* **Related APIs**: [Realtime Streaming Speech-to-Text](/api/api-guides-tutorials/speech-to-text/realtime-streaming) · [Instant Voice Cloning](/api/api-guides-tutorials/voice-cloning/overview) · [Prepare Reference Audio](/api/api-guides-tutorials/voice-cloning/how-to/prepare-reference-audio) · [Gemma 4 31B](/api/token-factory/models/gemma-4-31b)
* **Full source**: [Realtime_Speech_Dubbing on GitHub](https://github.com/sarvamai/sarvam-ai-cookbook/tree/main/examples/Realtime_Speech_Dubbing)
* **Community**: [Join the Discord Community](https://discord.com/invite/5rAsykttcs)

## **Final Notes**

* Keep your API key in `.env` or your shell, never in code or the UI.
* Dubbing runs sentence by sentence, not word by word, so each sentence plays a few seconds after you pause.
* Don't share the public Gradio link, since every request on it is billed to your key.

**Keep Building!** 🚀