Twilio gives you two ways to get text out of a live call. The built-in <Transcription> noun sends call audio to a speech-to-text engine Twilio picks and posts the results to a webhook. Media Streams hands you the raw audio over a WebSocket, so you choose the model, see every partial transcript as it arrives and keep the audio in your own pipeline.
This tutorial takes the Media Streams route. You'll build a small Node.js server that answers a Twilio number, receives the caller's audio and streams it to AssemblyAI-STT-3.7-Realtime, the streaming speech-to-text model built for live calls, meetings and captions. Words appear in your terminal while the caller is still talking.
The full code is in the companion repo, kelsey-aai/twilio-realtime-transcription-node.
Twilio <Transcription> or Media Streams?
Both start from TwiML on your phone number. They differ in what reaches your code.
| Twilio <Transcription> | Media Streams + AssemblyAI | |
|---|---|---|
| Speech model | Google or Deepgram, or auto (Twilio picks) |
You choose: assemblyai-stt-3-7-realtime |
| How results arrive | HTTP POSTs to your statusCallbackUrl |
WebSocket messages, partials and finals |
| Raw call audio | Not exposed to your code | Base64 mu-law frames you can store or reuse |
| Custom vocabulary | Provider-dependent hints | Up to 100 keyterms per session |
| You run | A webhook endpoint | A WebSocket server |
Pick <Transcription> when a webhook of finished utterances is all you need. Pick Media Streams when you want a specific model, live partials for a screen or an agent assist panel, keyterms for your product and customer names, or the audio itself.
How the pieces fit
- A caller dials your Twilio number.
- Twilio requests your webhook. Your server answers with TwiML containing
<Connect><Stream>. - Twilio opens a WebSocket to your server and sends
connected, thenstart, then a run ofmediamessages, thenstopwhen the call ends. - Your server opens one AssemblyAI streaming session per call and forwards the audio.
- AssemblyAI sends back
Turnmessages: partials while the caller talks, and a final when the turn ends.
Twilio's docs fix the audio format for every stream: audio/x-mulaw, 8000 Hz, one channel, base64-encoded in each media message. AssemblyAI accepts mu-law at 8 kHz directly (encoding: "pcm_mulaw", sampleRate: 8000), so there's no decoding or resampling step. Send phone audio at its native rate. Upsampling it to 16 kHz adds no information and the docs advise against it.
Before you start
You need:
- Node.js 18 or later
- A Twilio account and a phone number with voice capability
- ngrok, or any other way to give your local server a public HTTPS URL
- An AssemblyAI API key. Sign up and new accounts get $50 in free credits for the speech APIs.
AssemblyAI-STT-3.7-Realtime costs $0.30/hr, billed on session duration. See pricing for current rates.
Sign up to get an API key and $50 in free credits, then stream your first Twilio call to AssemblyAI-STT-3.7-Realtime.
Step 1: Set up the project
Clone the repo, or create an empty folder and add the files below by hand.
git clone https://github.com/kelsey-aai/twilio-realtime-transcription-node.git
cd twilio-realtime-transcription-node
npm install
cp .env.example .envpackage.json pins four dependencies: the AssemblyAI SDK, Express for the webhook, ws for the Media Streams WebSocket and dotenv for configuration.
{
"name": "twilio-realtime-transcription-node",
"version": "1.0.0",
"description": "Transcribe Twilio phone calls in real time with AssemblyAI-STT-3.7-Realtime",
"type": "module",
"main": "transcribe.js",
"scripts": {
"start": "node transcribe.js"
},
"engines": {
"node": ">=18"
},
"dependencies": {
"assemblyai": "^4.43.0",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"ws": "^8.18.0"
},
"license": "MIT"
}Open .env and paste your API key. KEYTERMS is optional; leave it empty for now.
ASSEMBLYAI_API_KEY=replace-this
# Optional: terms your callers say often, comma-separated
KEYTERMS=Step 2: Write the server
Here's the whole server, transcribe.js. The sections after it walk through each part.
// Transcribe Twilio phone calls in real time with AssemblyAI-STT-3.7-Realtime.
import "dotenv/config";
import http from "node:http";
import express from "express";
import { WebSocketServer } from "ws";
import { AssemblyAI } from "assemblyai";
const PORT = Number(process.env.PORT ?? 8080);
// Optional: comma-separated terms your callers say often.
const KEYTERMS = (process.env.KEYTERMS ?? "")
.split(",")
.map((t) => t.trim())
.filter(Boolean);
const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY });
const app = express();
// Twilio calls this webhook when your number rings.
// <Connect><Stream> sends the caller's audio to our WebSocket.
app.post("/", (req, res) => {
res.type("text/xml").send(`<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Speak to see your words transcribed in the console.</Say>
<Connect>
<Stream url="wss://${req.headers.host}/media" />
</Connect>
</Response>`);
});
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: "/media" });
wss.on("connection", (twilioWs) => {
let transcriber = null;
let buffer = Buffer.alloc(0);
const BUFFER_BYTES = 800; // 100 ms of 8 kHz mu-law (one byte per sample)
twilioWs.on("message", async (raw) => {
const msg = JSON.parse(raw.toString());
switch (msg.event) {
case "start": {
const fmt = msg.start.mediaFormat;
console.log(`Call ${msg.start.callSid} started (${fmt.encoding}, ${fmt.sampleRate} Hz)`);
transcriber = client.streaming.transcriber({
speechModel: "assemblyai-stt-3-7-realtime",
encoding: "pcm_mulaw", // Twilio's format, sent as-is
sampleRate: 8000, // no upsampling
// The SDK sends this list as one JSON-encoded keyterms_prompt parameter.
...(KEYTERMS.length ? { keytermsPrompt: KEYTERMS } : {}),
});
transcriber.on("open", ({ id }) => console.log(`AssemblyAI session ${id}`));
transcriber.on("error", (err) => console.error("AssemblyAI error:", err));
transcriber.on("close", (code, reason) => console.log(`\nSession closed (${code}) ${reason}`));
transcriber.on("turn", (turn) => {
const text = turn.transcript.trim();
if (!text) return; // 3.7 Realtime can send an empty final after noise
if (turn.end_of_turn) {
process.stdout.write(`\r\x1b[K${text}\n`); // final: keep it
} else {
process.stdout.write(`\r\x1b[K${text}`); // partial: replace the line
}
});
try {
await transcriber.connect();
} catch (err) {
console.error("Could not connect to AssemblyAI:", err.message);
transcriber = null;
}
break;
}
case "media": {
if (!transcriber) return;
buffer = Buffer.concat([buffer, Buffer.from(msg.media.payload, "base64")]);
if (buffer.length >= BUFFER_BYTES) {
transcriber.sendAudio(buffer);
buffer = Buffer.alloc(0);
}
break;
}
case "stop": {
console.log("\nCall ended");
if (transcriber) {
if (buffer.length) transcriber.sendAudio(buffer);
await transcriber.close(); // sends Terminate and waits for the session to end
transcriber = null;
}
break;
}
}
});
twilioWs.on("close", async () => {
if (transcriber) await transcriber.close().catch(() => {});
});
});
server.listen(PORT, () => console.log(`Listening on port ${PORT}`));The TwiML webhook
When your number rings, Twilio POSTs to /. The response tells Twilio to say a short prompt and then connect the call's audio to wss://<your host>/media.
Twilio's <Stream> docs set three rules worth knowing here. The URL must use wss. It can't carry a query string, so pass any per-call values as nested <Parameter> elements, which arrive in the start message. And with <Connect><Stream>, Twilio holds the call on the stream and runs no further TwiML until your server closes the WebSocket. Only the caller's (inbound) audio is sent.
One AssemblyAI session per call
The start message carries the call SID and the media format. That's the point to open the AssemblyAI session, with four settings:
speechModel: "assemblyai-stt-3-7-realtime". Leave this out and the session runs on the API's default model, so set it explicitly. The model selection docs list AssemblyAI-STT-3.7-Realtime for live captions, notetakers and ambient transcription, and AssemblyAI-STT-3.7-Realtime-Agent for voice agents.encoding: "pcm_mulaw"andsampleRate: 8000, matching what Twilio sends.keytermsPrompt, only when you've setKEYTERMS. The SDK sends the list as one JSON-encodedkeyterms_promptquery parameter.
Buffering the audio
Each Twilio media message holds a small slice of audio. The streaming docs accept 20 to 1,000 ms per message and recommend 50 to 100 ms, so the server collects about 100 ms before sending. Mu-law uses one byte per sample, which makes 100 ms at 8 kHz exactly 800 bytes.
Partials and finals
Every Turn message carries the transcript of the whole turn so far, so each one replaces the last. The turn detection docs say to render that way: overwrite, never append. The server rewrites one terminal line for partials (end_of_turn: false) and moves to a new line when the final arrives (end_of_turn: true). The final is fully formatted and the most accurate version of the turn, so store that one.
On AssemblyAI-STT-3.7-Realtime, the first partial arrives about 0.8 seconds after speech starts and then roughly once a second. Background noise can occasionally produce an empty final, which the code skips.
Hanging up
On stop, the server flushes any buffered audio and calls transcriber.close(). That sends Terminate and waits for the session to end, so the last turn is finalized before the connection closes.
Step 3: Run it and call your number
Start the server:
npm startIn a second terminal, open a tunnel to port 8080:
ngrok http 8080Copy the HTTPS forwarding URL. In the Twilio Console, open Phone Numbers > Manage > Active numbers, select your number, and under Voice Configuration set "A call comes in" to Webhook, paste the URL, choose HTTP POST and save. If you use the Twilio CLI, this does the same:
twilio phone-numbers:update "+15555550123" --voice-url "https://your-subdomain.ngrok-free.app/"Call the number and talk. Your terminal shows something like this:
Listening on port 8080
Call CA3f... started (audio/x-mulaw, 8000 Hz)
AssemblyAI session 3207b601-2054-48df-ba77-8784dfcf9fb8
Hi, I'm calling about my order from last Tuesday.
The tracking number ends in 4417.Stream your microphone in the playground to hear how the model handles your accent, names and numbers before you wire up a phone line.
Tune it for your calls
Keyterms. If callers say product names, company names or people's names the model gets wrong, list them in .env:
KEYTERMS=Acme Freight,Okafor,LTL quoteThe prompting and keyterms docs allow up to 100 terms of 50 characters or fewer, and recommend starting with none and adding only terms the model keeps missing. Long lists of common words can cause overcorrections. The post on when keyterm prompting backfires shows what that looks like.
Mode. Turn detection defaults to the balanced preset, a good fit for live display. If the transcript feeds notes or post-call analysis and a little more delay is fine, add mode: "max_accuracy" to the transcriber options. The accuracy and latency docs describe each preset.
Turn length. On this model, turns end on content: a finished sentence ends the turn, and a turn that ends partway through a phone number or other entity is held open. maxTurnSilence caps how long it waits. The end-of-turn check never runs before 320 ms of silence, so minTurnSilence values below 320 have no effect here. Leave both unset unless your transcripts split in the wrong places.
Why AssemblyAI-STT-3.7-Realtime for phone calls
AssemblyAI-STT-3.7-Realtime is built for live conversations, including calls. In the launch benchmarks, it posted a 3.23% word error rate on short-form English, ahead of ElevenLabs Scribe v3 Live, AWS Transcribe Streaming and Deepgram Flux. On unscripted telephone calls it had the lowest live diarization error rate of the realtime providers measured (10.46%), ahead of ElevenLabs Scribe v3 Live and Meta Muse Voice Transcribe. One stream handles 32 languages with automatic detection, so a caller who switches languages mid-call stays in one session.
If the caller should talk to an AI agent instead of being transcribed, switch to AssemblyAI-STT-3.7-Realtime-Agent. The Twilio phone agent tutorial builds that version.
Taking it to production
- Both sides of the call.
<Connect><Stream>only carries the caller's audio. To transcribe a call between two people, fork it with<Start><Stream track="both_tracks">instead. Twilio then continues with the next TwiML instruction (for example a<Dial>) and labels eachmediamessageinboundoroutbound. Open one AssemblyAI session per track and you get the speaker split from the channels. For one mixed channel with several voices, AssemblyAI-STT-3.7-Realtime also supports live speaker labels. - Validate webhooks. Check the
X-Twilio-Signatureheader on the TwiML endpoint so only Twilio can request it. - Store finals, not partials. Write each final
Turnto your database with the call SID from thestartmessage. - Scale out. Each call holds two WebSockets open for its whole length. Run several instances behind a load balancer that supports WebSockets.
- Post-call work. Send the stored transcript to LLM Gateway for summaries or tagging once the call ends. If you don't need live results at all, batch transcription of the call recording is the simpler path.
The same server in other languages: Python with Flask and Go.
Clone the repo, add your API key and get live transcripts of your Twilio calls with AssemblyAI-STT-3.7-Realtime in a few minutes.
Frequently Asked Questions (FAQs)
Can Twilio transcribe calls in real time on its own?
Yes. Twilio's <Transcription> TwiML noun transcribes live calls with Google or Deepgram engines and posts utterances to a webhook. Use Media Streams with AssemblyAI when you want to choose the model, receive partials over a WebSocket, add keyterms or keep the raw audio.
What audio format does Twilio Media Streams send?
Twilio sends 8 kHz, single-channel mu-law audio (audio/x-mulaw), base64-encoded inside JSON media messages. AssemblyAI accepts it directly with encoding: "pcm_mulaw" and sampleRate: 8000, so you don't need to convert or resample it.
Should I upsample Twilio audio to 16 kHz before sending it?
No. Send phone audio at its native 8 kHz. AssemblyAI's docs say telephone audio should go in as-is, because upsampling adds no information and can reduce accuracy.
Which AssemblyAI model should I use for Twilio calls?
Use AssemblyAI-STT-3.7-Realtime (assemblyai-stt-3-7-realtime) to transcribe calls for display, notes or analytics. Use AssemblyAI-STT-3.7-Realtime-Agent (assemblyai-stt-3-7-realtime-agent) when the caller is talking to a voice agent. Set the model explicitly so the session doesn't fall back to the API default.
How much does real-time Twilio call transcription cost with AssemblyAI?
AssemblyAI-STT-3.7-Realtime is $0.30 per hour, billed on how long the streaming session is open. New accounts get $50 in free credits. Twilio bills separately for the phone number and call minutes.
How do I transcribe both the caller and the agent?
Use <Start><Stream track="both_tracks"> instead of <Connect><Stream>. Twilio sends inbound and outbound audio as separate tracks, so you can open one AssemblyAI session per track and attribute every line to the right side of the call.