How Full-Duplex WebSocket Audio Streaming Works in the OpenAI Realtime API
Full-duplex WebSocket streaming maintains a persistent, bidirectional event stream between your Node.js/TypeScript backend (or client) and the Realtime API so audio input can be streamed continuously while model audio deltas, transcripts, and function calls arrive simultaneously without waiting for turn-based HTTP round trips.
- Bidirectional client and server events: Instead of sending a single audio blob and waiting for one response, you stream
input_audio_buffer.appendchunks continuously while listening for server events such asinput_audio_buffer.speech_started,response.audio.delta,response.audio_transcript.delta, andresponse.done. - Server-side Voice Activity Detection (VAD) and barge-in: When semantic or server VAD detects that the user started speaking (
input_audio_buffer.speech_started), your orchestration layer can immediately sendresponse.canceland clear local playback buffers so the assistant stops talking smoothly instead of speaking over the user. - Audio format and sample-rate alignment: PCM16 (
pcm16, typically 24 kHz mono little-endian) org711_ulaw/g711_alawframes must match the configured session format and chunk cadence (for example, 20ms–100ms chunks) to avoid audio pops, buffer underruns, or drift.
Steps to Build a Full-Duplex Realtime Audio Relay in Node.js / TypeScript
- Open an authenticated WebSocket connection to the Realtime endpoint: Connect with
wss://api.openai.com/v1/realtime?model=...and passAuthorization: Bearer ...plus required Realtime beta/session headers (OpenAI-Beta: realtime=v1). - Send
session.updateimmediately on open: Configuremodalities(["text", "audio"]),voice,input_audio_format,output_audio_format,turn_detection(such asserver_vad),instructions, and anytoolsbefore streaming audio frames. - Stream microphone/client PCM chunks and handle barge-in: Forward incoming binary/base64 audio chunks via
input_audio_buffer.append, and wheninput_audio_buffer.speech_startedfires, cancel any active assistant response and clear queued outbound audio. - Stream outbound audio deltas and handle lifecycle cleanup: Decode base64
response.audio.deltachunks to forward to the audio sink, listen forerrorandresponse.function_call_arguments.doneevents, and clean up sockets/timers oncloseor client disconnect.
TypeScript Example: Full-Duplex Realtime WebSocket Session Manager
import WebSocket from "ws";
export interface RealtimeBridgeOptions {
apiKey: string;
model?: string;
voice?: "alloy" | "ash" | "ballad" | "coral" | "echo" | "sage" | "shimmer" | "verse";
instructions: string;
onAssistantAudioPcm16: (pcmChunk: Buffer) => void;
onAssistantTranscriptDelta?: (delta: string) => void;
onUserSpeechStarted?: () => void;
onError?: (err: unknown) => void;
}
export class RealtimeAudioBridge {
private ws: WebSocket | null = null;
private isOpen = false;
private activeResponseId: string | null = null;
private readonly pendingOutboundEvents: string[] = [];
constructor(private readonly opts: RealtimeBridgeOptions) {}
connect(): Promise<void> {
const model = this.opts.model ?? "gpt-4o-realtime-preview";
const url = `wss://[api.openai.com/v1/realtime?model=$](https://api.openai.com/v1/realtime?model=$){encodeURIComponent(model)}`;
return new Promise((resolve, reject) => {
const ws = new WebSocket(url, {
headers: {
Authorization: `Bearer ${this.opts.apiKey}`,
"OpenAI-Beta": "realtime=v1",
},
});
this.ws = ws;
ws.on("open", () => {
this.isOpen = true;
this.sendEvent({
type: "session.update",
session: {
modalities: ["text", "audio"],
voice: this.opts.voice ?? "alloy",
input_audio_format: "pcm16",
output_audio_format: "pcm16",
instructions: this.opts.instructions,
turn_detection: {
type: "server_vad",
threshold: 0.5,
prefix_padding_ms: 300,
silence_duration_ms: 500,
},
},
});
this.flushPendingEvents();
resolve();
});
ws.on("message", (raw) => {
this.handleServerEvent(raw.toString());
});
ws.on("error", (err) => {
this.opts.onError?.(err);
if (!this.isOpen) reject(err);
});
ws.on("close", () => {
this.isOpen = false;
this.activeResponseId = null;
});
});
}
appendInputAudio(pcm16Chunk: Buffer): void {
if (pcm16Chunk.length === 0) return;
this.sendEvent({
type: "input_audio_buffer.append",
audio: pcm16Chunk.toString("base64"),
});
}
interruptAssistant(): void {
if (this.activeResponseId) {
this.sendEvent({ type: "response.cancel" });
this.activeResponseId = null;
}
}
close(): void {
this.pendingOutboundEvents.length = 0;
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.close(1000, "Session closed");
}
this.ws = null;
this.isOpen = false;
}
private sendEvent(payload: Record<string, unknown>): void {
const serialized = JSON.stringify(payload);
if (this.ws && this.ws.readyState === WebSocket.OPEN && this.isOpen) {
this.ws.send(serialized);
} else {
this.pendingOutboundEvents.push(serialized);
}
}
private flushPendingEvents(): void {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
while (this.pendingOutboundEvents.length > 0) {
const next = this.pendingOutboundEvents.shift();
if (next) this.ws.send(next);
}
}
private handleServerEvent(rawMessage: string): void {
let event: Record<string, any>;
try {
event = JSON.parse(rawMessage);
} catch (err) {
this.opts.onError?.(err);
return;
}
switch (event.type) {
case "input_audio_buffer.speech_started": {
this.interruptAssistant();
this.opts.onUserSpeechStarted?.();
break;
}
case "response.created": {
this.activeResponseId = event.response?.id ?? null;
break;
}
case "response.audio.delta": {
if (typeof event.delta === "string" && event.delta.length > 0) {
this.opts.onAssistantAudioPcm16(Buffer.from(event.delta, "base64"));
}
break;
}
case "response.audio_transcript.delta": {
if (typeof event.delta === "string") {
this.opts.onAssistantTranscriptDelta?.(event.delta);
}
break;
}
case "response.done":
case "response.cancelled": {
this.activeResponseId = null;
break;
}
case "error": {
this.opts.onError?.(event.error ?? event);
break;
}
default:
break;
}
}
}
Helpful Tips for Production Realtime Audio Orchestration
- Never expose long-lived API keys to browser/mobile clients: Mint short-lived ephemeral client tokens on your backend when connecting directly from browsers, or keep the upstream WebSocket inside a trusted Node.js relay server.
- Bound outbound audio queues on slow clients: If a downstream network socket stalls while the model streams fast audio deltas, cap or drop stale queued frames on barge-in so memory usage stays bounded and voice playback never lags behind real time.
- Handle reconnects and session duration limits gracefully: Realtime WebSocket sessions have maximum lifetime caps and transient network drops—persist conversation state/transcripts externally and re-establish a clean session with updated context when needed.
You must log in or register to comment.
