Skip to content
Gemini 4 Live Translate: Dub a WAV File in Python — ContentBuffer guide

Gemini 4 Live Translate: Dub a WAV File in Python

K
Kodetra Technologies··12 min read Intermediate

Summary

Stream audio into Gemini 4 Live Translate, save the dubbed WAV, log transcripts, and meter cost.

Google shipped Gemini 4 Live and Gemini 4 Live Translate on December 2, and the translate model is the one developers have been poking at since. It takes a stream of speech in, and sends back speech in another language while the speaker is still talking. Google says the first translated audio now arrives in under two seconds, down from over three, across 70+ languages.

Most demos stop at "talk into your mic and hear Spanish". That is fun for a minute and hard to build on. This guide does something you can put in a pipeline: feed a WAV file through gemini-4-live-translate, save the dubbed audio as a new WAV, keep both transcripts, and print what the run cost. You also get a dry-run mode that exercises the whole pipeline offline, so you can test your plumbing without a key or a bill.

One thing to know up front: the official Live Translate guide still shows the older gemini-3.5-live-translate-preview ID in every sample. The Gemini 4 Live Translate model page says to swap in gemini-4-live-translate with no other code changes. That is what we do here.

What you'll build

  • dub.py: one WAV in, one translated WAV out, plus a JSON report with transcripts, time to first audio, and cost.
  • A --dry-run flag backed by a fake session, so the send/receive loop is testable in CI.
  • dub_many.py: the same clip dubbed into Spanish, Brazilian Portuguese and Japanese at once, one Live session per language.

Prerequisites

  • Python 3.10 or newer. The code below was run on 3.13.
  • pip install -U google-genai. The TranslationConfig type used here exists in google-genai 3.7.0, which is what this guide was checked against. If types.TranslationConfig is missing, your SDK is too old.
  • A Gemini API key in GEMINI_API_KEY for live runs. The model page lists a free tier for Live Translate (your data is used to improve Google products on that tier) and a paid tier.
  • ffmpeg, only if your source audio is not already 16 kHz mono 16-bit PCM.

How Live Translate differs from a normal Live session

If you have used the Live API for voice agents, forget most of it. Live Translate is a narrower thing, and the constraints shape the code.

AspectLive TranslateWhat it means for you
InputAudio only. Text input is not supported.You cannot send a string and get speech back. Use a TTS model for that.
Instructions and toolsNo system instructions, no function calling, no grounding.You cannot tell it to "keep product names in English". Fix terms in post-processing.
OutputAudio, with optional transcripts of both sides.Text comes only from input_transcription and output_transcription.
Language controltarget_language_code only. Source is auto-detected.One session per target language.
VoiceBy default it mirrors each speaker's voice.Dubbed output sounds like the original speaker unless you set a preset voice.

There are no turns in the chat sense either. Audio flows in, translated audio flows out with a short lag, and neither side waits for the other. That is why the script below has a sender task and a receiver task running at the same time.

Step 1: Get the audio format right

The docs are specific. Input is raw 16-bit PCM, 16 kHz, mono, little-endian, with MIME type audio/pcm;rate=16000, sent in 100 ms chunks. Output comes back as raw 16-bit PCM at 24 kHz mono. At 16 kHz and two bytes per sample, 100 ms is 3,200 bytes.

Convert anything else before you start:

ffmpeg -i interview.mp3 -ac 1 -ar 16000 -sample_fmt s16 interview_16k.wav

To follow along without a recording, this writes a six-second test clip. It is a tone, so the live model will have nothing to translate, but it is exactly the right shape for the dry run.

"""Write a 6-second, 16 kHz mono 16-bit test clip (a tone, so no mic needed)."""
import math, struct, wave

RATE, SECONDS = 16_000, 6
with wave.open("clip_16k.wav", "wb") as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(RATE)
    for n in range(RATE * SECONDS):
        w.writeframes(struct.pack("<h", int(9000 * math.sin(2 * math.pi * 220 * n / RATE))))
print("wrote clip_16k.wav")

Step 2: Constants, validation and the cost formula

Start dub.py with the numbers that matter. The model page prices Live Translate audio at $3.50 per million input tokens and $21.00 per million output tokens, billed at 25 audio tokens per second. That works out to $0.0053 per minute in, $0.0315 per minute out, about $0.0368 per minute of two-way audio.

"""Dub a WAV file into another language with Gemini 4 Live Translate.

    python dub.py clip_16k.wav --to es            # live, needs GEMINI_API_KEY
    python dub.py clip_16k.wav --to es --dry-run  # offline pipeline test, costs nothing
"""
import argparse, asyncio, json, math, struct, time, wave
from types import SimpleNamespace

MODEL = "gemini-4-live-translate"
IN_RATE, OUT_RATE = 16_000, 24_000          # input PCM rate, output PCM rate
CHUNK_MS = 100                              # docs: send 100 ms chunks
CHUNK_BYTES = IN_RATE * 2 * CHUNK_MS // 1000  # 16-bit mono -> 3200 bytes
TOKENS_PER_SEC = 25                         # audio billing rate
USD_IN, USD_OUT = 3.50, 21.00               # per 1M audio tokens, paid tier
IDLE_SECONDS = 4.0                          # stop after this much silence from the server


def read_pcm(path):
    with wave.open(path, "rb") as w:
        fmt = (w.getnchannels(), w.getsampwidth(), w.getframerate())
        if fmt != (1, 2, IN_RATE):
            raise SystemExit(
                f"{path}: need mono 16-bit {IN_RATE} Hz, got {fmt}. Convert with:\n"
                f"  ffmpeg -i {path} -ac 1 -ar {IN_RATE} -sample_fmt s16 fixed.wav")
        return w.readframes(w.getnframes())


def cost_usd(in_seconds, out_seconds):
    return (in_seconds * TOKENS_PER_SEC * USD_IN
            + out_seconds * TOKENS_PER_SEC * USD_OUT) / 1_000_000

read_pcm fails fast on the wrong format and prints the ffmpeg command to fix it. Sending 44.1 kHz stereo bytes labelled as 16 kHz mono does not raise an error. The model just hears slowed-down noise, and you pay for it.

Step 3: The send and receive loop

This is the core. dub() takes any object with send_realtime_input() and receive(), which is what makes the dry run possible later.

async def dub(session, pcm, out_path, make_blob):
    """Pump pcm into the session in real time; collect audio and transcripts."""
    audio_out, src_text, dst_text = bytearray(), [], []
    first_audio_at = None
    started = time.monotonic()
    last_msg = time.monotonic()
    done_sending = asyncio.Event()

    async def sender():
        for i in range(0, len(pcm), CHUNK_BYTES):
            await session.send_realtime_input(audio=make_blob(pcm[i:i + CHUNK_BYTES]))
            await asyncio.sleep(CHUNK_MS / 1000)       # pace like a live microphone
        await session.send_realtime_input(audio_stream_end=True)
        done_sending.set()

    async def receiver():
        nonlocal first_audio_at, last_msg
        while True:                                    # receive() ends per turn; re-enter
            async for msg in session.receive():
                last_msg = time.monotonic()
                sc = msg.server_content
                if not sc:
                    continue
                if sc.input_transcription and sc.input_transcription.text:
                    src_text.append(sc.input_transcription.text)
                if sc.output_transcription and sc.output_transcription.text:
                    dst_text.append(sc.output_transcription.text)
                if sc.model_turn:
                    for part in sc.model_turn.parts or []:
                        if part.inline_data and part.inline_data.data:
                            if first_audio_at is None:
                                first_audio_at = time.monotonic() - started
                            audio_out.extend(part.inline_data.data)

    async def watchdog():
        await done_sending.wait()
        while time.monotonic() - last_msg < IDLE_SECONDS:
            await asyncio.sleep(0.25)

    send_task = asyncio.create_task(sender())
    recv_task = asyncio.create_task(receiver())
    try:
        await watchdog()
    finally:
        for t in (send_task, recv_task):
            t.cancel()
        await asyncio.gather(send_task, recv_task, return_exceptions=True)

    with wave.open(out_path, "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(OUT_RATE)
        w.writeframes(bytes(audio_out))

    in_s = len(pcm) / (IN_RATE * 2)
    out_s = len(audio_out) / (OUT_RATE * 2)
    return {
        "input_seconds": round(in_s, 2),
        "output_seconds": round(out_s, 2),
        "first_audio_seconds": None if first_audio_at is None else round(first_audio_at, 2),
        "cost_usd": round(cost_usd(in_s, out_s), 6),
        "source_transcript": "".join(src_text).strip(),
        "translated_transcript": "".join(dst_text).strip(),
        "output_file": out_path,
    }

Three details here are easy to get wrong.

  • Pace the sender. The asyncio.sleep(0.1) between chunks makes the file arrive the way a microphone would. This is a real-time model. A one-minute clip takes about a minute to dub, and that is by design.
  • Re-enter receive(). In the Python SDK, session.receive() is a generator that stops when the server marks an interaction complete. A single async for can exit while audio is still coming. The outer while True goes back in.
  • Decide when you are done. A translation stream has no "final answer" message you can rely on. The script sends audio_stream_end=True after the last chunk to flush buffered audio, then a watchdog waits until the server has been quiet for four seconds. Translated speech trails the source, so cutting off the moment you finish sending loses the last sentence.

Step 4: Connect to gemini-4-live-translate

The config is small because the model does one thing. response_modalities must be ["AUDIO"]. The two transcription configs are empty objects whose presence turns transcripts on. translation_config carries the target language as a BCP-47 code such as es, pt-BR, ja or zh-Hans.

async def run(path, target, dry_run):
    pcm = read_pcm(path)
    out_path = f"{path.rsplit('.', 1)[0]}.{target}.wav"
    if dry_run:
        blob = lambda b: SimpleNamespace(data=b)
        return await dub(FakeSession(), pcm, out_path, blob)

    from google import genai
    from google.genai import types

    client = genai.Client()                            # reads GEMINI_API_KEY
    config = types.LiveConnectConfig(
        response_modalities=["AUDIO"],
        input_audio_transcription=types.AudioTranscriptionConfig(),
        output_audio_transcription=types.AudioTranscriptionConfig(),
        translation_config=types.TranslationConfig(
            target_language_code=target,
            echo_target_language=False,
        ),
    )
    blob = lambda b: types.Blob(data=b, mime_type=f"audio/pcm;rate={IN_RATE}")
    async with client.aio.live.connect(model=MODEL, config=config) as session:
        return await dub(session, pcm, out_path, blob)

echo_target_language controls what happens when the speaker is already talking in the target language. With False (the default) the model stays silent for those stretches. With True it repeats them, which is what you want for a dub that should have no gaps. The docs warn that echo mode can add artifacts when there is background noise or music.

Finish the file with a small CLI:

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("wav")
    ap.add_argument("--to", default="es", help="BCP-47 target code, e.g. es, pt-BR, ja")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()
    print(json.dumps(asyncio.run(run(args.wav, args.to, args.dry_run)),
                     indent=2, ensure_ascii=False))

Step 5: Add a dry run so you can test without spending

Real-time audio code fails in boring ways: a wrong chunk size, a task that never gets cancelled, a WAV header with the wrong rate. None of that needs a model to catch. FakeSession has the same two methods dub() uses, answers one second of tone for each second it hears, and returns messages with the same attribute shape as the SDK's LiveServerMessage.

class FakeSession:
    """Offline stand-in with the same surface dub() touches on the real session."""

    def __init__(self):
        self.q = asyncio.Queue()
        self.sent = 0

    async def send_realtime_input(self, *, audio=None, audio_stream_end=None):
        if audio is not None:
            self.sent += len(audio.data)
            if self.sent % (CHUNK_BYTES * 10) == 0:      # one reply per second heard
                sec = self.sent // (CHUNK_BYTES * 10)
                tone = b"".join(
                    struct.pack("<h", int(8000 * math.sin(2 * math.pi * 330 * n / OUT_RATE)))
                    for n in range(OUT_RATE))
                await self.q.put(self._msg(f"[source second {sec}] ",
                                           f"[translated second {sec}] ", tone))

    @staticmethod
    def _msg(src, dst, pcm):
        part = SimpleNamespace(inline_data=SimpleNamespace(data=pcm))
        return SimpleNamespace(server_content=SimpleNamespace(
            input_transcription=SimpleNamespace(text=src),
            output_transcription=SimpleNamespace(text=dst),
            model_turn=SimpleNamespace(parts=[part])))

    async def receive(self):
        while True:
            yield await self.q.get()

Put this class above dub() in the file. Then run it:

python make_clip.py
python dub.py clip_16k.wav --to es --dry-run

This is the actual output from that command:

wrote clip_16k.wav
{
  "input_seconds": 6.0,
  "output_seconds": 6.0,
  "first_audio_seconds": 0.92,
  "cost_usd": 0.003675,
  "source_transcript": "[source second 1] [source second 2] [source second 3] [source second 4] [source second 5] [source second 6]",
  "translated_transcript": "[translated second 1] [translated second 2] [translated second 3] [translated second 4] [translated second 5] [translated second 6]",
  "output_file": "clip_16k.es.wav"
}

The run took about ten seconds: six seconds of paced sending plus the four-second idle wait. clip_16k.es.wav is a valid 24 kHz mono file six seconds long. The cost line is the real formula applied to six seconds each way: 150 input tokens and 150 output tokens come to $0.003675.

Be clear about what the dry run proves. It proves your file handling, pacing, shutdown and cost math. The 0.92 s "first audio" is the fake's own timing and says nothing about the model. Drop --dry-run with a real speech clip and the same JSON comes back with real transcripts, a real time-to-first-audio you can compare against Google's under-two-seconds claim, and an output length that will differ from the input because languages do not take the same time to say the same thing.

Worked example: one announcement, three languages

Say you record a 45-second product update in English and want Spanish, Brazilian Portuguese and Japanese versions for regional channels. A session has one target language, so you open three. They are independent WebSocket connections, so they can run side by side and the whole job still takes about as long as the clip.

"""Dub one clip into several languages at once, one Live session per language."""
import asyncio, sys
from dub import run

TARGETS = ["es", "pt-BR", "ja"]

async def main(path, dry_run):
    results = await asyncio.gather(
        *(run(path, t, dry_run) for t in TARGETS), return_exceptions=True)
    total = 0.0
    print(f"{'lang':<7}{'in s':>7}{'out s':>8}{'first audio':>13}{'cost $':>10}")
    for target, r in zip(TARGETS, results):
        if isinstance(r, Exception):
            print(f"{target:<7}FAILED: {r}")
            continue
        total += r["cost_usd"]
        print(f"{target:<7}{r['input_seconds']:>7}{r['output_seconds']:>8}"
              f"{r['first_audio_seconds']:>13}{r['cost_usd']:>10.6f}")
    print(f"total ${total:.6f}")

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1], "--dry-run" in sys.argv))
python dub_many.py clip_16k.wav --dry-run
lang      in s   out s  first audio    cost $
es         6.0     6.0         0.93  0.003675
pt-BR      6.0     6.0         0.93  0.003675
ja         6.0     6.0         0.93  0.003675
total $0.011025

That is the dry-run output for the six-second test clip. For the real 45-second announcement, budget from the formula: 45 seconds in and roughly 45 seconds out is about $0.028 per language, so about eight cents for all three. An hour of audio dubbed into one language is about $2.21 at the paid rate.

return_exceptions=True matters here. If the Japanese session drops, you still get the other two files and a clear line saying which one to retry.

Choosing a voice

Out of the box, Live Translate replicates the speaker's voice in the target language. For a dub that is usually what you want. If you would rather have a fixed narrator, the model page says to set speechConfig with a preset voice name from the library of more than 2,000 voices. Voices you created through the custom voices endpoint are not supported for translation.

The translate docs do not show the Python for this. The general Live API form is below, and it validates against the SDK's LiveConnectConfig, but treat the combination with translation_config as something to confirm on your own account:

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    translation_config=types.TranslationConfig(target_language_code="es"),
    speech_config=types.SpeechConfig(
        voice_config=types.VoiceConfig(
            prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
        )
    ),
)

Common pitfalls

  • Copying the model ID from the guide page. The Live Translate guide samples still say gemini-3.5-live-translate-preview. The Gemini 4 model page lists gemini-4-live-translate as the stable ID and a drop-in replacement.
  • Assuming a Gemini 4 Live ID. This guide only covers the translate model. Google's launch post does not print the conversational model's API ID, so check the model list in AI Studio before you hard-code one.
  • Sending text. send_realtime_input(text=...) exists in the SDK, but Live Translate takes audio only.
  • Expecting it to follow instructions. No system prompt, no tools. If a brand name gets translated, fix it in the transcript or re-record. You cannot prompt your way out.
  • Trusting the detected source language. Detection can misfire on accents, similar languages and fast switching. The docs note the input transcript's language can be wrong while the translation is still fine. Do not route on it.
  • Long files in one session. The general Live API docs cap audio-only sessions at 15 minutes. For longer recordings, split on silence into segments under that limit and stitch the output WAVs.
  • Multi-speaker audio. Voice replication can drift, pick the wrong gender after a long pause, or stick to one voice when speakers alternate quickly. For panel recordings, a preset voice is the safer choice.
  • Music and background noise. Background audio is not always filtered out, and echo mode makes it worse. Clean the track first.
  • Shipping your API key to a browser. For client-side apps, mint an ephemeral token on your server. For Live Translate the token must use v1beta, and by default the translation_config you set in live_connect_constraints is locked into the token.
  • Forgetting the watermark. Every output stream carries a SynthID audio watermark. Fine for most uses, worth knowing if you run audio forensics downstream.

Quick reference

ItemValue
Model IDgemini-4-live-translate
Connectclient.aio.live.connect(model=..., config=...)
Input audio16-bit PCM, 16 kHz, mono, audio/pcm;rate=16000, 100 ms chunks (3,200 bytes)
Output audio16-bit PCM, 24 kHz, mono
Target languageTranslationConfig(target_language_code="es"), BCP-47, default en
Echo same-language speechecho_target_language=True (default False)
Transcriptsinput_audio_transcription and output_audio_transcription set to AudioTranscriptionConfig()
Sendsession.send_realtime_input(audio=types.Blob(...)), then audio_stream_end=True
Receiveserver_content.model_turn.parts[].inline_data.data, .input_transcription.text, .output_transcription.text
Billing25 audio tokens per second; $3.50 / 1M in, $21.00 / 1M out; about $0.0368 per minute both ways
Not supportedText input, system instructions, tools, custom-created voices
Languages70+

Next steps

  • Swap the WAV reader for a microphone stream (sounddevice or PyAudio at 16 kHz) and play the 24 kHz output through speakers for a live interpreter.
  • Write source_transcript and translated_transcript out as a bilingual subtitle file. You already have both strings.
  • Record first_audio_seconds across 20 real clips and compare the median to the under-two-seconds figure in Google's launch post.
  • Add a pytest that runs dub() against FakeSession and asserts the output WAV's rate and length, so pipeline regressions get caught before they cost money.

Sources

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,631 newsletter subscribers.

Also get