On this page

Audio streaming

Connect a session to a phone call, a LiveKit room or your own WebSocket, so live audio flows in and speech flows back out.

A transport carries live audio between a session and the outside world. Once you connect one, incoming audio goes to the provider for recognition, and anything the session says goes back out the same way.

Transports

TransportImport fromCarries audio for
twilioMediaStream(ws)voiceai-sdk/twilioA phone call, over Twilio Media Streams
livekitRoom(room, { identity })voiceai-sdk/livekitA LiveKit room, which the session joins as a participant named identity
webSocketAudio(ws)voiceai-sdk/wsYour own client, streaming raw audio over a WebSocket

A transport only moves audio. The provider you pass to createSession still does the recognition and the speech. See Twilio and LiveKit for setup on each side.

Connect a session

Create the session, then pass a transport to session.connect. From then on the session reads audio from the transport and writes speech to it.

TypeScript
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";
import { twilioMediaStream } from "voiceai-sdk/twilio";

Bun.serve({
  port: 3000,
  fetch: (req, server) => (server.upgrade(req) ? undefined : new Response("upgrade required", { status: 426 })),
  websocket: {
    async open(ws) {
      await using session = await createSession(deepgram(), { sampleRate: 8000, encoding: "mulaw" });
      session.connect(twilioMediaStream(ws));

      await session.say`Thanks for calling. How can I help?`;
      await session.converse(async (text) => `You said: ${text}`);
    },
  },
});

Twilio opens one WebSocket per call. Phone audio is 8 kHz μ-law, so the session is set to match. When the caller hangs up, the socket closes, converse resolves, and await using closes the session.

How audio flows

Text
caller ──audio──▶ transport ──▶ session ──▶ provider (speech-to-text)
caller ◀──audio── transport ◀── session ◀── provider (text-to-speech)
  1. The transport receives audio from the caller and hands it to the session.
  2. The session streams it to the provider and receives partial and final transcripts.
  3. Voice activity detection marks where the caller starts and stops talking.
  4. Each final transcript goes to your converse handler.
  5. What the handler returns, and anything you pass to say, is synthesized and sent back through the transport.

In a pipeline, the top row goes to the stt provider and the bottom row to the tts provider.

Encodings and sample rates

encoding and sampleRate tell the session what format its audio is in. Set them to match your source, so the provider receives audio it can read.

encodingWhat it isTypical source
pcm16Uncompressed 16-bit samplesYour own app or browser client, raw files
mulaw8-bit compressed telephone audioPhone calls
opusCompressed audio made for the networkWebRTC clients, stored speech

sampleRate is 8000, 16000, 24000 or 48000. Use the rate your source records at. If the provider can't accept the rate or encoding you ask for, createSession throws VoiceError with code unsupported. Latency and audio formats covers the trade-offs.

Without a transport

You don't need a transport to stream. listen takes any AsyncIterable<Uint8Array> or ReadableStream, and iterating speak gives you audio chunks to send wherever you like. This example reads raw audio from stdin and writes the reply to stdout:

TypeScript
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";

await using session = await createSession(deepgram(), { sampleRate: 16000, encoding: "pcm16" });

for await (const t of session.listen(process.stdin)) {
  if (t.type !== "final") continue;
  for await (const chunk of session.speak(`You said: ${t.text}`)) process.stdout.write(chunk.data);
}

Use a transport when one exists for your source. It handles the framing for you.

Voice activity detection

Voice activity detection (VAD) decides when the caller is talking. It is on unless you pass vad: false. silenceMs sets how long a pause must last before the session treats the turn as over.

TypeScript
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";

await using session = await createSession(deepgram(), { vad: { silenceMs: 800 } });

session.on("transcript", (t) => t.type === "final" && console.log("turn ended:", t.text));
session.on("speech.start", () => console.log("reply started playing"));

A turn ends, and a final transcript arrives, once the caller has been quiet for silenceMs. speech.start and speech.end mark the session's own replies starting and finishing. A shorter pause answers sooner but can cut off a caller who stops to think. A longer one waits more patiently.

During converse, a caller who talks over the session stops its speech and fires interrupt. See Interruptions and barge-in. Whether a provider accepts a custom silenceMs depends on the provider; see Capabilities.

Next steps

Esc

Loading…

↑↓ navigate openCtrl J preview