MSMuhammad Shahid

Engineering notes

Building a Real-Time Voice Translation Web App with WebRTC and Whisper

By Muhammad Shahid · · 20 min read

Quick answer

To build a real-time voice translation web app, capture the microphone in the browser, open a WebRTC connection straight to OpenAI's gpt-realtime-translate model using a short-lived client secret minted by your server, play the translated speech from the remote audio track and show captions from the data channel. Whisper is not the right tool for live translation: its translation endpoint takes a finished recording, outputs English only, and is deprecated with a shutdown date of 26 February 2027.

Key facts
StackBrowser WebRTC, Node.js, Express 5, zod, gpt-realtime-translate
Price$0.034 per audio minute, per target language (OpenAI model page, November 2026)
Whisper/v1/audio/translations outputs English only and shuts down on 26 February 2027
SecurityThe standard API key stays on the server; the browser gets a one-session client secret
TestedReal Chrome with a fake microphone against a local WebRTC stand-in for OpenAI

Live voice translation used to mean gluing three services together: speech-to-text, a translation model and text-to-speech, each adding its own delay. In 2026 OpenAI offers a model built for exactly this job, and the browser can talk to it directly over WebRTC. This tutorial builds a complete real-time voice translation web app: a small Node.js server that mints short-lived secrets, a browser client that streams the microphone and plays the translated voice, and live captions in both languages. It also explains where Whisper fits today, because most tutorials that come up for this search still use it, and its translation endpoint does not do what people expect. All code is complete and type-checked. It was run in real Google Chrome with a fake microphone against a local WebRTC stand-in for OpenAI's endpoints, so the browser, WebRTC and caption code is tested; the translation quality and latency of the real model are not measured here.

Why build live translation on WebRTC?

WebRTC is the browser's built-in protocol for real-time audio and video. It handles the hard parts of live audio for you: the Opus codec, jitter buffers, packet loss and echo cancellation. Sending audio over WebRTC means the microphone stream goes out continuously and the translated voice comes back as an ordinary audio track that an <audio> element can play, with no manual encoding, chunking or base64. OpenAI's translation guide covers WebRTC for browser apps and a WebSocket interface for servers that already have the audio, such as a phone system.

What happened to Whisper?

Comparison of four ways to translate speech: the Whisper API translates a finished recording into English only and shuts down on 26 February 2027; open-source Whisper runs on your own hardware but its translate task also outputs English only; a three-step pipeline gives full control but adds delays; gpt-realtime-translate streams voice in and translated voice and text out for $0.034 per audio minute
Whisper translates into English only. For live translation into other languages, use a streaming model.

Whisper is a speech recognition model, and its "translate" mode was always narrow: it turns speech in any supported language into English text. It cannot translate English into Spanish, and it works on a finished recording or a chunk of audio, not a live stream. OpenAI's speech-to-text guide now lists whisper-1 and the /v1/audio/translations endpoint as deprecated, with a shutdown date of 26 February 2027, and names gpt-realtime-translate as the replacement for translation. The open-source Whisper models (run with whisper.cpp or faster-whisper) are still useful when audio must stay on your own hardware, but their translate task has the same English-only limit.

The architecture

Architecture: the browser asks your server for a session, the server mints a client secret from OpenAI with the standard key, then the browser sends its SDP offer to OpenAI and streams the microphone over WebRTC, receiving translated voice on an audio track and captions on the data channel
Your server hands out a secret; the audio itself goes straight between the browser and OpenAI.

Your server does one thing: it turns your secret API key into a short-lived client secret for one translation session into one language. The browser uses that secret to set up the WebRTC call with OpenAI directly, so audio never passes through your server and you do not pay for the bandwidth or the latency of a relay. The real API key never reaches the browser.

What do you need?

ToolVersion usedWhy
Node.js20 or laterThe session server
Express5Serves the page and POST /session
zod4Validates the target language
An OpenAI API keyWith access to gpt-realtime-translateMints client secrets (server only)
A modern browserChrome, Edge, Safari or FirefoxgetUserMedia and RTCPeerConnection
HTTPSor localhostBrowsers only allow the microphone on secure pages

Step 1: Set up the project

mkdir live-translate && cd live-translate && npm init -y && npm pkg set type=module
npm install express@5 zod
npm install -D typescript tsx @types/node @types/express
mkdir -p src public

Step 2: Mint a client secret on the server

import express from "express";
import { z } from "zod";

// The target languages your interface offers. One translation session translates into one language,
// so a new language means a new session. Test each language with real speakers before you list it.
export const TARGETS = ["en", "es", "fr", "de", "it", "pt", "hi", "ar", "zh", "ja", "ru"] as const;

const Body = z.object({ targetLanguage: z.enum(TARGETS) });

export function createApp(opts: { apiKey: string; openaiBase?: string }) {
  const base = opts.openaiBase ?? "https://api.openai.com";
  const app = express();
  app.use(express.json({ limit: "2kb" }));
  app.use(express.static("public"));

  // Mint a short-lived client secret for one translation session.
  // The standard API key never leaves the server; the browser only sees the ephemeral value.
  app.post("/session", async (req, res) => {
    const parsed = Body.safeParse(req.body);
    if (!parsed.success) {
      res.status(400).json({ error: "Unsupported target language" });
      return;
    }
    try {
      const r = await fetch(base + "/v1/realtime/translations/client_secrets", {
        method: "POST",
        headers: { Authorization: "Bearer " + opts.apiKey, "Content-Type": "application/json" },
        body: JSON.stringify({
          session: { model: "gpt-realtime-translate", audio: { output: { language: parsed.data.targetLanguage } } },
        }),
        signal: AbortSignal.timeout(10_000),
      });
      if (!r.ok) {
        console.error("client_secrets failed", r.status, await r.text());
        res.status(502).json({ error: "Could not start a translation session" });
        return;
      }
      const { value } = (await r.json()) as { value: string };
      res.set("Cache-Control", "no-store");
      res.json({ value });
    } catch (err) {
      console.error(err);
      res.status(502).json({ error: "Could not start a translation session" });
    }
  });

  return app;
}

// Run with: OPENAI_API_KEY=sk-... npx tsx src/server.ts
if (import.meta.url === "file://" + process.argv[1]) {
  const key = process.env.OPENAI_API_KEY;
  if (!key) throw new Error("Set OPENAI_API_KEY");
  createApp({ apiKey: key }).listen(3000, () => console.log("http://localhost:3000"));
}

The endpoint accepts only a language from your own list, so a visitor cannot open sessions in arbitrary languages, then calls /v1/realtime/translations/client_secrets with the standard key and returns only the value field. Cache-Control: no-store keeps the secret out of caches, and a 10-second timeout stops a slow upstream from holding requests open. Each session is billed by the minute, so in production put this route behind your login and a per-user rate limit; the guide to securing AI APIs has a Redis token bucket you can reuse here.

Step 3: Connect the browser over WebRTC

// @ts-check
// Browser side: microphone -> WebRTC -> gpt-realtime-translate -> translated speech and captions.
const CALLS_URL = "https://api.openai.com/v1/realtime/translations/calls";

/**
 * @param {{
 *   targetLanguage: string,
 *   audioEl: HTMLAudioElement,
 *   onCaption: (kind: "source" | "translated", delta: string) => void,
 *   onState?: (state: string) => void,
 * }} opts
 */
export async function startTranslation(opts) {
  const report = opts.onState ?? (() => {});

  // 1. Microphone, with the browser's echo cancellation so the translated voice is not translated again
  const mic = await navigator.mediaDevices.getUserMedia({
    audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
  });

  // 2. Peer connection: our audio goes out as a track, the translated speech comes back as a track
  const pc = new RTCPeerConnection();
  pc.addTrack(mic.getAudioTracks()[0], mic);
  pc.ontrack = ({ streams }) => {
    opts.audioEl.srcObject = streams[0];
  };
  pc.onconnectionstatechange = () => report(pc.connectionState);

  // 3. Events (captions, errors) arrive on a data channel created before the offer
  const events = pc.createDataChannel("oai-events");
  /** @type {(() => void) | null} */
  let onClosed = null;
  events.onmessage = (msg) => {
    const ev = JSON.parse(msg.data);
    if (ev.type === "session.input_transcript.delta") opts.onCaption("source", ev.delta);
    else if (ev.type === "session.output_transcript.delta") opts.onCaption("translated", ev.delta);
    else if (ev.type === "session.closed") onClosed?.();
    else if (ev.type === "error") report("error: " + (ev.error?.code ?? ev.error?.message ?? "unknown"));
  };

  let stopped = false;
  // Flush: ask the service to finish pending audio, wait up to 3 s for session.closed, then hang up.
  async function stop() {
    if (stopped) return;
    stopped = true;
    mic.getAudioTracks().forEach((t) => (t.enabled = false)); // send silence, keep the track
    if (events.readyState === "open") {
      const closed = new Promise((resolve) => {
        onClosed = () => resolve(true);
        setTimeout(() => resolve(false), 3000);
      });
      events.send(JSON.stringify({ type: "session.close" }));
      await closed;
    }
    mic.getTracks().forEach((t) => t.stop());
    pc.close();
    report("closed");
  }

  try {
    // 4. A short-lived secret from our server: the real API key never reaches the browser
    const s = await fetch("/session", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ targetLanguage: opts.targetLanguage }),
    });
    if (!s.ok) throw new Error("Session request failed: " + s.status);
    const { value } = await s.json();

    // 5. SDP offer/answer, straight between the browser and OpenAI
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    const answer = await fetch(CALLS_URL, {
      method: "POST",
      body: offer.sdp,
      headers: { Authorization: "Bearer " + value, "Content-Type": "application/sdp" },
    });
    if (!answer.ok) throw new Error("Call setup failed: " + answer.status);
    await pc.setRemoteDescription({ type: "answer", sdp: await answer.text() });
  } catch (err) {
    stopped = true;
    mic.getTracks().forEach((t) => t.stop());
    pc.close();
    throw err;
  }

  return { stop, pc };
}

The order matters. The data channel oai-events must exist before the offer is created, or it will not be part of the connection. The microphone track is added the same way, so the offer describes one outgoing audio stream, and ontrack receives the translated voice as a remote stream. The SDP offer goes to /v1/realtime/translations/calls with the client secret as the bearer token, and the answer text goes into setRemoteDescription. If anything fails, the microphone is released and the connection closed, so the browser's recording indicator does not stay on.

Echo cancellation is not optional here: without it, the translated voice coming out of the speakers goes back into the microphone and gets translated again. Headphones avoid the problem completely.

Step 4: Show live captions

// @ts-check
// A rolling subtitle built from streamed text deltas. When it grows past maxChars it drops the oldest
// text at a word or sentence boundary, so a caption never starts in the middle of a word.
export class CaptionTrack {
  /** @param {number} maxChars */
  constructor(maxChars = 160) {
    this.maxChars = maxChars;
    this.text = "";
  }

  /** @param {string} delta */
  push(delta) {
    this.text += delta;
    if (this.text.length > this.maxChars) {
      const rest = this.text.slice(this.text.length - this.maxChars);
      // First space or sentence mark (Latin or CJK) in what is left; cut just after it.
      const cut = rest.search(/[\s.!?。!?،؟]/);
      this.text = (cut >= 0 ? rest.slice(cut + 1) : rest).trimStart();
    }
    return this.text;
  }

  clear() {
    this.text = "";
  }
}

Caption text arrives as small fragments: session.input_transcript.delta for what the speaker said and session.output_transcript.delta for the translation. CaptionTrack joins them into a rolling subtitle and drops the oldest text at a space or a sentence mark, so the line never starts in the middle of a word. It also handles languages written without spaces, such as Chinese, by cutting after 。, ! or ?.

Step 5: The page

<!doctype html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Live voice translation</title>
<main>
  <label>Translate into
    <select id="lang">
      <option value="es">Spanish</option><option value="fr">French</option><option value="de">German</option>
      <option value="hi">Hindi</option><option value="ar">Arabic</option><option value="zh">Chinese</option>
      <option value="en">English</option>
    </select>
  </label>
  <button id="start">Start</button>
  <button id="stop" disabled>Stop</button>
  <p id="state" role="status">idle</p>
  <p><small>You said</small><br /><span id="source" lang=""></span></p>
  <p><small>Translation</small><br /><strong id="translated" aria-live="polite"></strong></p>
  <audio id="voice" autoplay></audio>
</main>
<script type="module">
  import { startTranslation } from "./translator.js";
  import { CaptionTrack } from "./captions.js";

  const $ = (id) => document.getElementById(id);
  const tracks = { source: new CaptionTrack(), translated: new CaptionTrack() };
  let call = null;

  $("start").onclick = async () => {
    $("start").disabled = true;
    tracks.source.clear();
    tracks.translated.clear();
    try {
      call = await startTranslation({
        targetLanguage: $("lang").value,
        audioEl: $("voice"),
        onCaption: (kind, delta) => ($(kind).textContent = tracks[kind].push(delta)),
        onState: (s) => ($("state").textContent = s),
      });
      $("stop").disabled = false;
    } catch (err) {
      $("state").textContent = String(err.message ?? err);
      $("start").disabled = false;
    }
  };

  $("stop").onclick = async () => {
    $("stop").disabled = true;
    await call?.stop();
    $("start").disabled = false;
  };
</script>

The translated caption uses aria-live="polite", so screen readers announce it without interrupting. The audio element plays automatically because the session starts from a click, which satisfies the browsers' autoplay rules.

How does one session flow?

Sequence diagram of one session: the browser opens the microphone and data channel, asks your server for a session, the server gets a client secret from OpenAI, the browser posts the SDP offer and gets the answer, audio and caption events flow, and on Stop the browser sends session.close, receives session.closed and hangs up
From Start to Stop: two HTTP requests to set up, then audio and events over one WebRTC connection.

When the user presses Stop, the client mutes the microphone track (so silence keeps flowing), sends session.close on the data channel and waits up to three seconds for session.closed. OpenAI's guide describes session.close as the way to flush pending audio in a translation session, so the last words still get translated. Only then does the client stop the microphone and close the peer connection.

Testing without an API key

// A stand-in for OpenAI's translation endpoints, so the browser code can be tested in real Chrome
// without an API key. It answers the SDP offer with a real WebRTC peer (werift), echoes the caller's
// audio back as the "translated" track and sends scripted caption events on the data channel.
import express from "express";
import { randomBytes } from "node:crypto";
import { RTCPeerConnection, RTCRtpCodecParameters } from "werift";

export const STANDARD_KEY = "sk-test-standard-key";
export const log: string[] = [];
export const secretRequests: unknown[] = [];

export function createMock(script: { source: string[]; translated: string[] }) {
  const secrets = new Set<string>();
  const app = express();

  app.post("/v1/realtime/translations/client_secrets", express.json(), (req, res) => {
    if (req.get("authorization") !== "Bearer " + STANDARD_KEY) return void res.status(401).json({ error: "bad key" });
    secretRequests.push(req.body);
    const value = "ek_" + randomBytes(12).toString("hex");
    secrets.add(value);
    res.json({ value });
  });

  app.post("/v1/realtime/translations/calls", express.text({ type: "application/sdp" }), async (req, res) => {
    const secret = (req.get("authorization") ?? "").replace("Bearer ", "");
    if (!secrets.has(secret)) return void res.status(401).send("bad client secret");
    secrets.delete(secret); // one call per secret

    const pc = new RTCPeerConnection({
      codecs: { audio: [new RTCRtpCodecParameters({ mimeType: "audio/opus", clockRate: 48000, channels: 2 })] },
    });
    let rtpIn = 0;
    pc.onRemoteTransceiverAdded.subscribe((t) => {
      t.setDirection("sendrecv");
      t.onTrack.subscribe((track) => {
        track.onReceiveRtp.subscribe((rtp) => {
          rtpIn++;
          void t.sender.sendRtp(rtp); // echo: stands in for translated speech
        });
      });
    });
    pc.onDataChannel.subscribe((dc) => {
      log.push("datachannel:" + dc.label);
      const send = (o: object) => dc.send(JSON.stringify(o));
      const play = () => {
        script.source.forEach((d, i) => setTimeout(() => send({ type: "session.input_transcript.delta", delta: d }), 100 + i * 60));
        script.translated.forEach((d, i) => setTimeout(() => send({ type: "session.output_transcript.delta", delta: d }), 400 + i * 60));
      };
      dc.stateChanged.subscribe((s) => s === "open" && play());
      if (dc.readyState === "open") play();
      dc.onMessage.subscribe((data) => {
        const ev = JSON.parse(String(data));
        log.push("client:" + ev.type + " rtpIn=" + rtpIn);
        if (ev.type === "session.close") setTimeout(() => send({ type: "session.closed" }), 150);
      });
    });

    await pc.setRemoteDescription({ type: "offer", sdp: req.body });
    await pc.setLocalDescription(await pc.createAnswer());
    res.type("application/sdp").send(pc.localDescription!.sdp);
  });

  return app;
}

The stand-in is a real WebRTC peer written with werift, a WebRTC implementation for Node.js. It answers the browser's SDP offer, echoes the microphone audio back as the "translated" track and sends scripted caption events, so every part of the browser code runs for real: getUserMedia, the offer and answer, the data channel, the remote track and the close handshake. Playwright reroutes the browser's request for api.openai.com to the stand-in, so the page code is the same as in production.

import assert from "node:assert/strict";
import { chromium } from "playwright-core";
import { createApp } from "../src/server";
import { CaptionTrack } from "../public/captions.js";
import { createMock, log, secretRequests, STANDARD_KEY } from "./mock-openai";

// 1) Captions: rolling text that never starts mid-word
const c = new CaptionTrack(20);
for (const d of ["Hola, ", "¿cómo ", "estás? ", "Muy bien, ", "gracias."]) c.push(d);
assert.equal(c.text, "Muy bien, gracias.");
const z = new CaptionTrack(8);
for (const d of ["你好。", "今天天气", "很好。"]) z.push(d);
assert.equal(z.text, "今天天气很好。");
console.log("captions: trimmed at word and sentence boundaries (Latin and Chinese)");

// 2) Mock OpenAI and the app
const mock = createMock({
  source: ["Hello, ", "where is ", "the train ", "station?"],
  translated: ["Hola, ", "¿dónde está ", "la estación ", "de tren?"],
});
const mockSrv = mock.listen(4310);
const appSrv = createApp({ apiKey: STANDARD_KEY, openaiBase: "http://localhost:4310" }).listen(4311);

const bad = await fetch("http://localhost:4311/session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ targetLanguage: "xx" }) });
assert.equal(bad.status, 400);
const good = await fetch("http://localhost:4311/session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ targetLanguage: "es" }) });
const goodBody = await good.json();
assert.equal(good.status, 200);
assert.match(goodBody.value, /^ek_/);
assert.equal(good.headers.get("cache-control"), "no-store");
assert.deepEqual(secretRequests[0], { session: { model: "gpt-realtime-translate", audio: { output: { language: "es" } } } });
console.log("session: 400 for an unknown language, 200 with an ephemeral secret, standard key stays on the server");

// 3) The real page in Chrome with a fake microphone
const browser = await chromium.launch({
  channel: "chrome",
  args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--autoplay-policy=no-user-gesture-required"],
});
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
const seen: string[] = [];
page.on("request", (r) => seen.push(r.url() + " " + JSON.stringify(r.headers()) + " " + (r.postData() ?? "")));
await page.route("https://api.openai.com/**", async (route) => {
  const cors = { "access-control-allow-origin": "*", "access-control-allow-headers": "authorization, content-type", "access-control-allow-methods": "POST" };
  if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers: cors });
  const url = route.request().url().replace("https://api.openai.com", "http://localhost:4310");
  const r = await route.fetch({ url });
  await route.fulfill({ response: r, headers: { ...r.headers(), ...cors } });
});
await page.goto("http://localhost:4311/");
await page.selectOption("#lang", "es");
const t0 = Date.now();
await page.click("#start");
await page.waitForFunction(() => document.getElementById("state")!.textContent === "connected", null, { timeout: 15000 });
const connectMs = Date.now() - t0;
await page.waitForFunction(() => document.getElementById("translated")!.textContent!.endsWith("de tren?"), null, { timeout: 5000 });
const ui = await page.evaluate(async () => {
  const a = document.getElementById("voice") as HTMLAudioElement;
  const t1 = a.currentTime;
  await new Promise((r) => setTimeout(r, 1000));
  const track = (a.srcObject as MediaStream | null)?.getAudioTracks()[0];
  return {
    source: document.getElementById("source")!.textContent,
    translated: document.getElementById("translated")!.textContent,
    trackLive: track?.readyState,
    playing: a.currentTime > t1,
  };
});
assert.equal(ui.source, "Hello, where is the train station?");
assert.equal(ui.translated, "Hola, ¿dónde está la estación de tren?");
assert.equal(ui.trackLive, "live");
assert.equal(ui.playing, true);
console.log("browser: connected in", connectMs, "ms (local mock), remote audio track live and playing, captions:", JSON.stringify(ui.translated));

await page.click("#stop");
await page.waitForFunction(() => document.getElementById("state")!.textContent === "closed", null, { timeout: 5000 });
const closeLog = log.find((l) => l.startsWith("client:session.close"));
assert.ok(closeLog);
const rtpIn = Number(closeLog!.split("rtpIn=")[1]);
assert.ok(rtpIn > 0);
assert.ok(log.includes("datachannel:oai-events"));
console.log("stop: session.close sent after", rtpIn, "audio packets, session.closed received, call closed");

// 4) The standard key never reached the browser
assert.ok(!seen.some((s) => s.includes(STANDARD_KEY)));
assert.ok(seen.some((s) => s.includes("/v1/realtime/translations/calls") && s.includes("Bearer ek_")));
console.log("security: the browser only ever sent the ephemeral secret");

await browser.close();
mockSrv.close();
appSrv.close();
console.log("ALL TRANSLATION TESTS PASS");
process.exit(0);
npm install -D werift playwright-core   # test only: a WebRTC peer in Node, and Chrome automation
npx tsx test/translate.test.ts             # needs Google Chrome, no API key
OPENAI_API_KEY=sk-... npx tsx src/server.ts  # the real thing on http://localhost:3000

Output:

captions: trimmed at word and sentence boundaries (Latin and Chinese)
session: 400 for an unknown language, 200 with an ephemeral secret, standard key stays on the server
browser: connected in 796 ms (local mock), remote audio track live and playing, captions: "Hola, ¿dónde está la estación de tren?"
stop: session.close sent after 87 audio packets, session.closed received, call closed
security: the browser only ever sent the ephemeral secret
ALL TRANSLATION TESTS PASS

The test checks what the browser actually did: the translated audio track was live and playing, the captions read "Hola, ¿dónde está la estación de tren?", 87 audio packets reached the peer before session.close, and no request from the browser ever contained the standard API key. The 796 ms connection time is against a local peer and says nothing about OpenAI's latency.

What does it cost?

OpenAI's model page prices gpt-realtime-translate by audio duration, at $0.034 per minute in November 2026, rather than by tokens. One session translates into one language, so each target language is its own session and its own bill.

UsageMinutesCost at $0.034/min
One 30-minute meeting, one target language30$1.02
The same meeting for listeners in 3 languages90$3.06
100 users, 10 minutes a day, 30 days30,000$1,020 a month
1,000 users, 10 minutes a day, 30 days300,000$10,200 a month

Check the model page before you plan a budget, because prices change. To compare it with a text pipeline, the AI API cost calculator works out token costs for the transcribe-and-translate route. Usage limits are counted in minutes of audio per minute and grow with your account tier.

Latency: what to measure

OpenAI's guide does not publish latency figures, and they depend on the network, the language pair and how people speak, so measure them in your own app. The guide names three numbers worth tracking: the delay before the first translated audio, the delay after a speaker stops before the translation ends, and how well captions line up with the voice. Measure from the user's device, not your server, and keep the microphone streaming during pauses: the guide says to keep sending audio, silence included, because translation starts from the stream itself.

Production checklist

  • Keep the standard key on the server and mint one client secret per session.
  • Put /session behind login and a per-user rate limit: every session costs money by the minute.
  • Cap session length in the client and stop sessions when the tab is hidden for a long time.
  • Serve the page over HTTPS: browsers block the microphone elsewhere, except on localhost.
  • Tell users what is recorded and get consent before you translate other people's speech.
  • Handle error events and failed connections with a clear message and a retry button.
  • Test every language you offer with native speakers before you list it.

Common mistakes and how to fix them

MistakeWhat happensFix
Using the Whisper translation endpoint for live translationEnglish text only, after the recording endsUse gpt-realtime-translate over WebRTC
Putting the standard API key in the browserAnyone can copy it and spend your moneyMint a client secret on the server
Creating the data channel after the offerNo caption events arriveCall createDataChannel before createOffer
No echo cancellation and no headphonesThe translation gets translated againKeep echoCancellation on, or use headphones
Stopping the microphone at once on StopThe last words are lostSend session.close and wait for session.closed
One session for several target languagesOnly one language comes backOne session per target language
Testing only on localhostThe microphone is blocked on the real siteServe over HTTPS

Limitations

This build translates one speaker's microphone into one language. A two-way conversation needs two sessions, one for each direction. OpenAI's translation guide does not publish a list of supported languages or say how the source language is detected, so test every pair you plan to offer. The test in this article uses a stand-in for OpenAI and checks the browser and server code, not translation quality or real-world latency. Finally, any machine translation can get names, numbers and technical terms wrong; for medical, legal or financial conversations, show the original text alongside the translation and let people correct it.

When to use a pipeline or self-hosted Whisper instead

A streaming model is the right choice for live conversation. A three-step pipeline (transcribe with gpt-transcribe, translate with a text model, optionally speak with text-to-speech) is better when you need a glossary, a specific tone, a human review before anything is spoken, or written output such as subtitles for a recorded video; it is slower, because three calls run in a row. Self-hosted Whisper is the choice when audio must never leave your hardware, with the English-only limit on its translate task. The guide to streaming LLM responses in React shows how to stream the text step of a pipeline to the page.

Frequently asked questions

Can Whisper translate in real time?

Not on its own. The Whisper API translates a finished recording, and open-source Whisper works on chunks of audio. For live translation, use a streaming model such as gpt-realtime-translate.

Can Whisper translate English into other languages?

No. Whisper's translate task outputs English only. To translate into other languages, use gpt-realtime-translate, or transcribe and then translate the text with a language model.

Is the Whisper API being shut down?

OpenAI lists whisper-1 and the /v1/audio/translations endpoint as deprecated, with a shutdown date of 26 February 2027, and names gpt-realtime-translate as the translation replacement.

What is gpt-realtime-translate?

An OpenAI model that takes live speech and returns translated speech and text as a stream, over WebRTC or WebSocket, using the /v1/realtime/translations endpoints.

How much does real-time voice translation cost with OpenAI?

OpenAI's model page lists gpt-realtime-translate at $0.034 per audio minute in November 2026, so a 30-minute call into one language costs about $1.02. Each target language is a separate session.

Why use WebRTC instead of WebSocket in the browser?

WebRTC handles microphone audio, the Opus codec, jitter and echo cancellation for you and returns the translated voice as a normal audio track. WebSocket suits servers that already have the audio.

Is it safe to call OpenAI directly from the browser?

Yes, if the browser only gets a short-lived client secret minted by your server. Never put the standard API key in client code.

Can one session translate into several languages?

No. OpenAI's guide says to create one translation session for each target language.

How do I show live captions?

Read session.input_transcript.delta and session.output_transcript.delta events from the oai-events data channel and append the deltas to a rolling caption.

Why does the app translate its own output?

The speaker's output is reaching the microphone. Keep echoCancellation enabled in getUserMedia or use headphones.

How do I stop a session without losing the last words?

Send session.close on the data channel, wait for session.closed, then stop the microphone and close the peer connection.

Can I test the app without an OpenAI API key?

Yes. Run a local WebRTC peer, such as one built with werift, that answers the SDP offer and sends scripted events, and route the browser's OpenAI request to it, as this article's test does.

Sources

Free apps from the author of this guide