Transcribing phone calls (8 kHz, μ-law, Twilio, SIP)
The problem. A phone line carries 8 kHz audio in G.711: μ-law in North America and Japan, A-law almost everywhere else. Converting it to 16-bit PCM, or resampling it to 16 kHz, adds work and latency on your side and no detail the line never carried.
What the API does. Gladia’s live API takes telephony audio as the line carries it: set encoding to
wav/ulaw or wav/alaw, sample_rate to 8000 and bit_depth to 8, then send the bytes you receive. Put the
caller and the agent on two channels and each utterance says who spoke, with no diarization.
At a glance
Section titled “At a glance”| Live API | encoding |
|---|---|
| Pre-recorded (batch) | Upload the call recording (Transcribe a file) |
| Live models | solaria-3, trantoria-1 (every live model) |
| Languages | Every language of the model (supported languages) |
| Encodings | wav/ulaw and wav/alaw (G.711, bit_depth: 8), as the line carries them |
| Sample rate | 8000 Hz: send it as it is, never upsampled |
| Parties | channels: 2, one party per channel, interleaved (Multichannel) |
Step by step
Section titled “Step by step”1. Describe the line in the init body
Section titled “1. Describe the line in the init body”{ "encoding": "wav/ulaw", "sample_rate": 8000, "bit_depth": 8, "channels": 1, "model": "solaria-3" }A-law is the same with "encoding": "wav/alaw". The bytes go as they are: no WAV header, no conversion.
2. Stream a call
Section titled “2. Stream a call”The programs below turn a 16-bit WAV file into 8 kHz μ-law, as a phone line would, then stream it and print the
transcript. Put your API key in the GLADIA_API_KEY environment variable, then run python phone_call.py call.wav.
With a real line, send the μ-law bytes you receive instead.
# pip install -U "gladiaio-sdk>=2.2"import osimport sysimport threadingimport wave
from gladiaio_sdk import GladiaClient
API_URL = os.environ.get("GLADIA_API_URL", "https://eu1.api.gladia.io")API_KEY = os.environ["GLADIA_API_KEY"]LINE_RATE = 8000 # a phone line: 8 kHz
def ulaw(sample): """One 16-bit sample as G.711 μ-law (what a phone line carries).""" sample >>= 2 # G.711 works on 14 bits mask = 0x7F if sample < 0 else 0xFF magnitude = min(abs(sample), 8159) + 0x21 segment = 0 while segment < 8 and magnitude >= 0x40 << segment: segment += 1 if segment == 8: return 0x7F ^ mask return ((segment << 4) | ((magnitude >> (segment + 1)) & 0x0F)) ^ mask
with wave.open(sys.argv[1]) as wav: # a 16-bit PCM WAV file, mono, at 8, 16 or 48 kHz rate, frames = wav.getframerate(), wav.readframes(wav.getnframes())if rate % LINE_RATE: sys.exit(f"{rate} Hz: give a WAV file at a multiple of {LINE_RATE} Hz")samples = memoryview(frames).cast("h")step = rate // LINE_RATE # keep one sample in `step`, the mean of themline = bytes(ulaw(sum(samples[i : i + step]) // step) for i in range(0, len(samples) - step + 1, step))
config = {"encoding": "wav/ulaw", "sample_rate": LINE_RATE, "bit_depth": 8, "channels": 1, "model": "solaria-3"}client = GladiaClient(api_key=API_KEY, api_url=API_URL)session = client.live_v2().start_session(config)ended, errors = threading.Event(), []
@session.on("message")def on_message(message): if message.type == "transcript" and message.data.is_final: print(message.data.utterance.text)
session.on("error", errors.append)session.once("ended", lambda _: ended.set())
# Stream once the socket is open: a stop sent while it opens can pass the audio queued until then.connected = threading.Event()session.once("connected", lambda _: connected.set())session.once("ended", lambda _: connected.set()) # a session that never connects endssession.on("error", lambda _: connected.set())if session.status == "connected": # it opened before the listener above connected.set()if not connected.wait(timeout=30) or errors or ended.is_set(): sys.exit(1) # no open session to stream to
chunk = LINE_RATE // 10 # 100 ms of μ-law: 800 bytesfor start in range(0, len(line), chunk): session.send_audio(line[start : start + chunk]) # live audio: send each chunk as it arrivessession.stop_recording()
ended.wait(timeout=60)sys.exit(1 if errors or not ended.is_set() else 0)// npm install @gladiaio/sdkimport { readFileSync } from "node:fs";import { GladiaClient } from "@gladiaio/sdk";
const LINE_RATE = 8000; // a phone line: 8 kHzconst { sampleRate, pcm } = readWav(process.argv[2]); // a 16-bit PCM WAV file, mono, at 8, 16 or 48 kHzif (sampleRate % LINE_RATE) throw new Error(`${sampleRate} Hz: give a WAV file at a multiple of ${LINE_RATE} Hz`);
// One 16-bit sample as G.711 μ-law (what a phone line carries).function ulaw(sample) { sample >>= 2; // G.711 works on 14 bits const mask = sample < 0 ? 0x7f : 0xff; const magnitude = Math.min(Math.abs(sample), 8159) + 0x21; let segment = 0; while (segment < 8 && magnitude >= 0x40 << segment) segment += 1; if (segment === 8) return 0x7f ^ mask; return ((segment << 4) | ((magnitude >> (segment + 1)) & 0x0f)) ^ mask;}
const samples = new Int16Array(pcm.buffer, pcm.byteOffset, pcm.length / 2);const step = sampleRate / LINE_RATE; // keep one sample in `step`, the mean of themconst line = Buffer.alloc(Math.floor(samples.length / step));for (let i = 0; i < line.length; i += 1) { let sum = 0; for (let j = 0; j < step; j += 1) sum += samples[i * step + j]; line[i] = ulaw(Math.trunc(sum / step));}
const client = new GladiaClient({ apiKey: process.env.GLADIA_API_KEY, apiUrl: process.env.GLADIA_API_URL ?? "https://eu1.api.gladia.io",});const session = client.liveV2().startSession({ encoding: "wav/ulaw", sample_rate: LINE_RATE, bit_depth: 8, channels: 1, model: "solaria-3",});
session.on("message", (message) => { if (message.type === "transcript" && message.data.is_final) console.log(message.data.utterance.text);});session.on("error", (error) => { console.error(error); process.exitCode = 1;});session.once("ended", () => process.exit());
const chunk = LINE_RATE / 10; // 100 ms of μ-law: 800 bytesfor (let start = 0; start < line.length; start += chunk) { session.sendAudio(line.subarray(start, start + chunk)); // live audio: send each chunk as it arrives}session.stopRecording();
function readWav(path) { const file = readFileSync(path); let fmt, pcm; for (let pos = 12; pos < file.length; ) { const id = file.toString("ascii", pos, pos + 4); const size = file.readUInt32LE(pos + 4); if (id === "fmt ") fmt = { sampleRate: file.readUInt32LE(pos + 12) }; if (id === "data") pcm = file.subarray(pos + 8, pos + 8 + size); pos += 8 + size + (size % 2); } return { ...fmt, pcm };}Create the session, then stream its audio to the returned url (Live WebSocket):
curl -X POST https://eu1.api.gladia.io/v2/live \ -H "x-gladia-key: $GLADIA_API_KEY" \ -H "content-type: application/json" \ -d '{ "encoding": "wav/ulaw", "sample_rate": 8000, "bit_depth": 8, "channels": 1, "model": "solaria-3" }'3. Connect your telephony
Section titled “3. Connect your telephony”Twilio Media Streams. A <Start><Stream> in your TwiML sends the call to your WebSocket server as JSON messages: a
start, then media messages whose media.payload is base64 μ-law at 8 kHz, 20 ms each, then a stop. Your
server decodes each payload and sends the bytes to Gladia as they come. With track="both_tracks", Twilio sends the
caller (inbound) and your side (outbound) as separate messages: interleave them byte by byte into a 2-channel
stream, the caller on channel 0.
// npm install @gladiaio/sdk ws twilio// TwiML: <Start><Stream url="wss://your-server.example.com/twilio" track="both_tracks"/></Start>import { WebSocketServer } from "ws";import twilioSdk from "twilio";import { GladiaClient } from "@gladiaio/sdk";
const client = new GladiaClient({ apiKey: process.env.GLADIA_API_KEY });const FRAME = 160; // 20 ms of 8 kHz μ-law, the size of a Twilio media payloadconst MAX_LAG = FRAME * 25; // 500 ms: past it, the silent track is filled with silenceconst SILENCE = 0xff; // μ-law silenceconst PUBLIC_URL = "wss://your-server.example.com/twilio"; // the url of your <Stream>
// Only Twilio may open a stream (and spend your Gladia key): check its signature.const fromTwilio = ({ req }) => twilioSdk.validateRequest(process.env.TWILIO_AUTH_TOKEN, req.headers["x-twilio-signature"] ?? "", PUBLIC_URL, {});
new WebSocketServer({ port: 8080, path: "/twilio", verifyClient: fromTwilio }).on("connection", (twilio) => { // One Gladia session per call: the caller on channel 0, your side on channel 1. const session = client.liveV2().startSession({ encoding: "wav/ulaw", sample_rate: 8000, bit_depth: 8, channels: 2, model: "solaria-3", }); session.on("message", (message) => { if (message.type === "transcript" && message.data.is_final) { const { channel, text } = message.data.utterance; console.log(`${channel === 0 ? "Caller" : "Agent"}: ${text}`); } });
const pending = { inbound: Buffer.alloc(0), outbound: Buffer.alloc(0) }; twilio.on("message", (raw) => { const message = JSON.parse(raw.toString()); if (message.event === "media") { const track = message.media.track; // "inbound" (the caller) or "outbound" pending[track] = Buffer.concat([pending[track], Buffer.from(message.media.payload, "base64")]); // One track may stop sending (on hold, muted): fill it with silence so the other never waits long for (const [side, other] of [["inbound", "outbound"], ["outbound", "inbound"]]) { const lag = pending[side].length - pending[other].length; if (lag > MAX_LAG) pending[other] = Buffer.concat([pending[other], Buffer.alloc(lag, SILENCE)]); } // Interleave once both tracks have a frame: caller byte, agent byte, caller byte… while (pending.inbound.length >= FRAME && pending.outbound.length >= FRAME) { const stereo = Buffer.alloc(FRAME * 2); for (let i = 0; i < FRAME; i += 1) { stereo[2 * i] = pending.inbound[i]; stereo[2 * i + 1] = pending.outbound[i]; } pending.inbound = pending.inbound.subarray(FRAME); pending.outbound = pending.outbound.subarray(FRAME); session.sendAudio(stereo); } } if (message.event === "stop") flushAndStop(); }); twilio.on("close", flushAndStop);
// The call ended: send what is still buffered (the shorter track padded with silence), then stop. let stopped = false; function flushAndStop() { if (stopped) return; stopped = true; const length = Math.max(pending.inbound.length, pending.outbound.length); const pad = (track) => Buffer.concat([track, Buffer.alloc(length - track.length, SILENCE)]); const [inbound, outbound] = [pad(pending.inbound), pad(pending.outbound)]; const stereo = Buffer.alloc(length * 2); for (let i = 0; i < length; i += 1) { stereo[2 * i] = inbound[i]; stereo[2 * i + 1] = outbound[i]; } if (length) session.sendAudio(stereo); session.stopRecording(); }});SIP and your own media server. Gladia’s API does not answer SIP itself: your session border controller or media
server keeps the call and forks its audio to your code, which sends it to Gladia. Asterisk’s External Media and
AudioSocket, FreeSWITCH’s audio fork modules and most CPaaS media streams hand you raw G.711 frames: send them with
the init body of step 1, channels: 2 when you get both legs.
Limits and gotchas
Section titled “Limits and gotchas”- Send the line’s bytes, not a WAV file. No header, no container: a WAV header is read as audio.
bit_depthis8withwav/ulawandwav/alaw; any other value is refused with a400. - Do not upsample. Converting 8 kHz audio to 16 kHz adds no information; send it at
8000. - μ-law or A-law: match the line. Both are 8-bit and play as noise when swapped. North American and Japanese carriers (and Twilio) use μ-law; European ones usually A-law.
- Accept only Twilio. Your bridge opens Gladia sessions with your key: check the
X-Twilio-Signatureof each WebSocket request with your Twilio auth token, as the bridge above does, or anyone who finds its address transcribes on your account. - Twilio’s payload is base64. Decode it and send binary frames: base64 is a third larger and is not what the init body describes.
- Two parties, two channels. Interleaved byte by byte for 8-bit audio. Channels are transcribed on their own:
each utterance carries its
channel, and cross-talk does not mix the parties (Multichannel). One channel with both parties needs speaker diarization. - Silence on hold. A call on hold sends silence or nothing: keep the session open with keep_alive.