Overview
WebRTC uses UDP media transport with built-in jitter buffers, packet-loss recovery, and acoustic echo cancellation. On Wi-Fi or mobile networks, TCP-based WebSockets can stall when a packet drops, while WebRTC keeps voice smooth.
- Media over WebRTC, control events over DataChannel: Stream raw microphone and reply audio tracks over
RTCPeerConnectionand send JSON control events over anRTCDataChannel. - Short-lived session tokens on the server: Mint ephemeral client credentials on your Node.js/TypeScript backend so your main LLM API key never reaches the browser.
Steps
- Mint a short-lived client token on the server: Call your backend or provider client-secrets endpoint with your secret API key and return only a temporary token to the browser.
- Capture microphone audio and create
RTCPeerConnection: Enable browser echo cancellation and noise suppression, add the audio track, and attach a data channel for session and tool events. - Exchange SDP offer and answer: Send the browser’s SDP offer to the realtime WebRTC endpoint and apply the returned SDP answer to start media flow.
- Handle barge-in and clean teardown: Stop local playback when the user speaks over the model, and close tracks and peer connections on hangup.
Example
import express from "express";
// --- Server: Mint short-lived client token (Node.js / TypeScript) ---
export function createVoiceTokenRouter(openAiApiKey: string) {
const router = express.Router();
router.post("/api/voice/session", async (_req, res) => {
try {
const response = await fetch("[https://api.openai.com/v1/realtime/client_secrets](https://api.openai.com/v1/realtime/client_secrets)", {
method: "POST",
headers: {
Authorization: `Bearer ${openAiApiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ session: { type: "realtime", model: "gpt-realtime-2.1", }, }), }); if (!response.ok) { const text = await response.text(); res.status(response.status).json({ error: text }); return; } const data = (await response.json()) as { value?: string; client_secret?: { value?: string } }; const token = data.value ?? data.client_secret?.value; res.json({ token }); } catch (err) { res.status(500).json({ error: err instanceof Error ? err.message : "Token error" }); } }); return router; } // --- Browser: Connect mic and audio playback over WebRTC --- export class BrowserVoiceWebRtcClient { private pc: RTCPeerConnection \vert{} null = null; private dc: RTCDataChannel \vert{} null = null; private localStream: MediaStream \vert{} null = null; async connect(audioElement: HTMLAudioElement, onEvent?: (evt: unknown) => void): Promise<void> { const tokenRes = await fetch("/api/voice/session", { method: "POST" }); if (!tokenRes.ok) { throw new Error("Failed to fetch ephemeral voice token."); } const { token } = (await tokenRes.json()) as { token: string }; const pc = new RTCPeerConnection(); this.pc = pc; audioElement.autoplay = true; pc.ontrack = (event) => { const [remoteStream] = event.streams; if (remoteStream) { audioElement.srcObject = remoteStream; } }; const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }); this.localStream = stream; for (const track of stream.getAudioTracks()) { pc.addTrack(track, stream); } const dc = pc.createDataChannel("oai-events"); this.dc = dc; dc.onopen = () => { dc.send( JSON.stringify({ type: "session.update", session: { type: "realtime", instructions: "Keep answers short, clear, and spoken naturally.", }, }) ); }; dc.onmessage = (event) => { try { const parsed = JSON.parse(String(event.data)); onEvent?.(parsed); } catch { // Ignore non-JSON control frames } }; const offer = await pc.createOffer(); await pc.setLocalDescription(offer); const sdpResponse = await fetch("[https://api.openai.com/v1/realtime/calls](https://api.openai.com/v1/realtime/calls)", { method: "POST", headers: { Authorization: `Bearer ${token}`,
"Content-Type": "application/sdp",
},
body: offer.sdp,
});
if (!sdpResponse.ok) {
throw new Error(`SDP exchange failed: \${sdpResponse.status}`);
}
const answerSdp = await sdpResponse.text();
await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
}
sendEvent(payload: Record<string, unknown>): void {
if (this.dc && this.dc.readyState === "open") {
this.dc.send(JSON.stringify(payload));
}
}
disconnect(): void {
this.dc?.close();
this.dc = null;
this.localStream?.getTracks().forEach((t) => t.stop());
this.localStream = null;
this.pc?.close();
this.pc = null;
}
}
Tips
- Use HTTPS or
localhost: Browsers block microphone access (getUserMedia) on plain HTTP origins outsidelocalhost. - Set voice before audio starts: Lock your chosen voice in session setup before the first audio reply plays.
- Use WebSockets for server-to-server or phone bridges: Keep WebSockets for backend pipelines or SIP/telephony bridges where your server owns the audio stream.
You must log in or register to comment.
