Skip to navigation

Realtime Speech Dubbing

View as Markdown

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:

StageAPIWhat it does
ListenSaaras v4 Realtime StreamingTranscribes the microphone stream and detects when you stop speaking
TranslateGemma 4 on Token FactoryTranslates each finished sentence, using the previous three as context
SpeakInstant Voice CloningSpeaks 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

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

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

How It Works

1

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.

2

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.

3

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.

4

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 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 to get one
  • A browser with microphone access, and headphones

2. Clone and Install

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

3. Configure Environment Variables

Copy the example file and add your key:

cp .env.example .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

python app.py

Open the local URL Gradio prints, usually http://127.0.0.1:7860.

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

1

Pick languages

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

2

Optional: adjust Advanced options

Pick a saved voice, or change pause and reference settings. See Available Options.

3

Record

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

4

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.

5

Stop

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

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:

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:

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:

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

OptionDefaultWhat it does
Saved voice IDNoneNone 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.
Pause duration1.5 sSilence 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 duration12 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 noiseOnCleans 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.

Target language: the 12 languages Instant Voice Cloning supports:

LanguageCodeLanguageCode
Assameseas-INMalayalamml-IN
Bengalibn-INMarathimr-IN
Englishen-INOdiaod-IN
Gujaratigu-INPunjabipa-IN
Hindihi-INTamilta-IN
Kannadakn-INTelugute-IN

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.

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:

FileContents
combined-<id>.wavThe full dubbed session, written on Stop. Mono, 16 kHz.
playback-<id>.mp3One file per dubbed sentence, served to the player. These are not deleted automatically.
timings.jsonlOne 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.
  • 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.
  • 429 Too Many Requests (rate_limit_exceeded_error), too many requests. The app retries translation automatically; check Credits & 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.

Additional Resources

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! 🚀