How do you implement WebSocket bidirectional audio streaming with Realtime Voice LLM APIs in Node.js? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you implement WebSocket bidirectional audio streaming with Realtime Voice LLM APIs in Node.js?

message-square
0

How Bidirectional Audio Streaming Works Over WebSockets

Realtime Voice LLM APIs maintain a persistent, event-driven WebSocket connection so audio frames and control events can flow in both directions simultaneously while the model listens, detects speech turns, invokes tools, and streams back synthesized speech.

  • JSON control and media events over WebSocket: Instead of request/response HTTP calls, your Node.js server sends client events (session setup, audio chunks, response cancellations) and receives server events (speech activity markers, transcripts, audio deltas, and errors).
  • Base64-encoded PCM audio chunks: Raw PCM audio (commonly 16-bit signed little-endian mono at 24 kHz or matching your audio pipeline) is sliced into short frames (typically 20–100 ms), base64-encoded, and appended to the input audio buffer.
  • Server-side VAD and barge-in: With Voice Activity Detection enabled, the server detects when the user starts and stops speaking, commits the turn automatically, and lets your app cancel an active response when the user interrupts.
  • Full-duplex relay in Node.js: Your Node.js backend bridges an upstream audio client (WebSocket, WebRTC/SIP gateway, or browser/mobile relay) with the Realtime API WebSocket while managing backpressure, playback queue resets, and socket lifecycle cleanup.

Steps to Implement Bidirectional Audio Streaming in Node.js

  1. Connect to the Realtime WebSocket endpoint: Open an authenticated WebSocket connection to wss://api.openai.com/v1/realtime with model in the query string and Authorization: Bearer <API_KEY> in the headers.
  2. Initialize the session with session.update: On socket open, send session.update to configure instructions, input/output audio formats and sample rates, voice selection, turn detection (server_vad), and tool declarations.
  3. Stream incoming PCM audio via input_audio_buffer.append: Convert incoming raw PCM buffers to base64 and send input_audio_buffer.append events continuously as audio arrives.
  4. Process outbound audio and transcript deltas: Listen for response.output_audio.delta (or response.audio.delta), decode base64 back into PCM buffers for playback, and forward transcript deltas to your client or logs.
  5. Handle barge-in and clean up connections: When input_audio_buffer.speech_started fires, send response.cancel if a response is active and flush any queued outbound audio so the user hears the interruption immediately.

Node.js Example: Full-Duplex Realtime Voice WebSocket Relay

import WebSocket from "ws";

export function createRealtimeVoiceBridge({
  apiKey = process.env.OPENAI_API_KEY,
  model = "gpt-realtime",
  instructions = "You are a concise, helpful voice assistant.",
  voice = "alloy",
  onAudioChunk,
  onTranscriptDelta,
  onSpeechStarted,
}) {
  const url = `wss://[api.openai.com/v1/realtime?model=\$](https://api.openai.com/v1/realtime?model=$){encodeURIComponent(model)}`;

  const ws = new WebSocket(url, {
    headers: {
      Authorization: `Bearer \${apiKey}`,
    },
  });

  let activeResponseId = null;

  const sendEvent = (payload) => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(payload));
    }
  };

  ws.on("open", () => {
    sendEvent({
      type: "session.update",
      session: {
        type: "realtime",
        instructions,
        audio: {
          input: {
            format: { type: "audio/pcm", rate: 24000 },
            turn_detection: {
              type: "server_vad",
              threshold: 0.5,
              prefix_padding_ms: 300,
              silence_duration_ms: 500,
            },
          },
          output: {
            format: { type: "audio/pcm", rate: 24000 },
            voice,
          },
        },
      },
    });
  });

  ws.on("message", (rawMessage) => {
    const event = JSON.parse(rawMessage.toString());

    switch (event.type) {
      case "input_audio_buffer.speech_started": {
        if (activeResponseId) {
          sendEvent({ type: "response.cancel" });
          activeResponseId = null;
        }
        onSpeechStarted?.();
        break;
      }

      case "response.created": {
        activeResponseId = event.response?.id ?? null;
        break;
      }

      case "response.output_audio.delta":
      case "response.audio.delta": {
        if (event.delta) {
          onAudioChunk?.(Buffer.from(event.delta, "base64"));
        }
        break;
      }

      case "response.output_audio_transcript.delta":
      case "response.audio_transcript.delta": {
        if (event.delta) {
          onTranscriptDelta?.(event.delta);
        }
        break;
      }

      case "response.done": {
        activeResponseId = null;
        break;
      }

      case "error": {
        console.error("Realtime API event error:", event.error);
        break;
      }
    }
  });

  ws.on("error", (err) => {
    console.error("Realtime WebSocket transport error:", err);
  });

  ws.on("close", (code, reason) => {
    console.log(`Realtime WebSocket closed (${code}):${reason.toString()}`);
  });

  return {
    sendPcmFrame(pcmBuffer) {
      const buf = Buffer.isBuffer(pcmBuffer) ? pcmBuffer : Buffer.from(pcmBuffer);
      if (buf.length === 0) return;
      sendEvent({
        type: "input_audio_buffer.append",
        audio: buf.toString("base64"),
      });
    },
    triggerManualResponse() {
      sendEvent({ type: "input_audio_buffer.commit" });
      sendEvent({ type: "response.create" });
    },
    close() {
      if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
        ws.close();
      }
    },
  };
}

Helpful Tips for Production Voice Pipelines

  • Match sample rates and PCM framing across legs: Ensure incoming audio from browsers, WebRTC, or telephony streams is resampled and framed cleanly to match your configured PCM sample rate (24000 Hz or your target rate) so audio does not speed up, slow down, or clip.
  • Clear client-side audio queues on barge-in: Sending response.cancel stops future server audio deltas, but your downstream audio player or socket bridge must also drop buffered outbound chunks on onSpeechStarted so stale speech stops immediately.
  • Guard against backpressure and reconnect cleanly: Monitor socket buffer state on slow clients, avoid sending huge audio bursts all at once, and tear down/recreate sessions cleanly when network connections drop.