Audio formats and examples
Audio format
Section titled “Audio format”A stream uses one audio format in both directions. It is set by the encoding and sampleRate attributes of <Stream>, and confirmed in start.media_format when the stream starts:
"media_format": { "encoding": "audio/x-mulaw", "sample_rate": 8000, "channels": 1 }Always decode and encode with the values from start.media_format. They can differ from what you asked for: a 16000 Hz request on a phone network call gives 8000 Hz.
encoding |
Sample format | sample_rate |
Bytes per 20 ms |
|---|---|---|---|
audio/x-mulaw (default) |
G.711 μ-law, 8 bits per sample | 8000 | 160 |
audio/L16 |
Signed 16-bit linear PCM, little-endian | 8000 | 320 |
audio/L16 |
Signed 16-bit linear PCM, little-endian | 16000 | 640 |
- Audio is always mono.
audio/L16samples are little-endian (least significant byte first). That is the native byte order of almost every computer, and the byte order of WAV files, but it is not the big-endian order that the name L16 means in RTP.- In each message, the audio is base64-encoded (standard alphabet, with padding) in
media.payload. - The
startmessage tells you the rate. 16000 Hz is only used withaudio/L16when you ask forsampleRate="16000"(or16k, orauto) and the call’s own codec carries wideband audio, for example G.722 or Opus from a browser or app. Phone network calls, and everyaudio/x-mulawstream, are 8000 Hz.
Which encoding to choose
Section titled “Which encoding to choose”audio/x-mulawif your speech service accepts μ-law 8 kHz (most telephony speech services do). It uses half the bandwidth of L16.audio/L16if your service wants linear PCM, or you want 16 kHz audio from wideband calls. Ask forsampleRate="16000"and handle both 8000 and 16000, because the rate depends on the call.
Sending audio
Section titled “Sending audio”In a two-way stream, the audio you send must use the stream’s encoding and sample rate, mono. If your text-to-speech service can produce that format directly (for example raw μ-law at 8000 Hz, or 16-bit PCM at the right rate), you can base64 it and send it as it is. Otherwise convert it first. You can send any amount of audio per message. Messages of 20 ms to 1 second work well. See Playback for how SIPRTC queues it.
To prepare a WAV prompt for the examples below, convert it to 16-bit mono PCM at the stream’s rate, for example with ffmpeg:
ffmpeg -i greeting.mp3 -ac 1 -ar 8000 -c:a pcm_s16le greeting.wavDecoding and encoding μ-law
Section titled “Decoding and encoding μ-law”μ-law needs a few lines of code. These functions convert between μ-law bytes and 16-bit PCM, and work for any audio/x-mulaw stream.
Node.js
Section titled “Node.js”audio.mjs. The examples below import these helpers. It needs no packages.
// audio.mjs: G.711 μ-law and WAV helpers for SIPRTC streams.import fs from 'node:fs';
// μ-law bytes -> 16-bit little-endian PCMexport function ulawToPcm16(ulaw) { const pcm = Buffer.alloc(ulaw.length * 2); for (let i = 0; i < ulaw.length; i++) { const u = ~ulaw[i] & 0xff; const exponent = (u >> 4) & 0x07; const mantissa = u & 0x0f; const magnitude = (((mantissa << 3) + 0x84) << exponent) - 0x84; pcm.writeInt16LE(u & 0x80 ? -magnitude : magnitude, i * 2); } return pcm;}
// 16-bit little-endian PCM -> μ-law bytesexport function pcm16ToUlaw(pcm) { const ulaw = Buffer.alloc(pcm.length >> 1); for (let i = 0; i < ulaw.length; i++) { let s = pcm.readInt16LE(i * 2); const sign = s < 0 ? 0x80 : 0; if (s < 0) s = -s; if (s > 32635) s = 32635; s += 0x84; let exponent = 7; for (let mask = 0x4000; exponent > 0 && !(s & mask); mask >>= 1) exponent--; const mantissa = (s >> (exponent + 3)) & 0x0f; ulaw[i] = ~(sign | (exponent << 4) | mantissa) & 0xff; } return ulaw;}
// Decode a media payload to 16-bit PCM, whatever the stream's encoding.export function payloadToPcm16(payload, mediaFormat) { const audio = Buffer.from(payload, 'base64'); return mediaFormat.encoding === 'audio/x-mulaw' ? ulawToPcm16(audio) : audio;}
// Encode 16-bit PCM in the stream's encoding, as base64 for media.payload.export function pcm16ToPayload(pcm, mediaFormat) { const audio = mediaFormat.encoding === 'audio/x-mulaw' ? pcm16ToUlaw(pcm) : pcm; return audio.toString('base64');}
// Write 16-bit mono PCM to a WAV file.export function writeWav(path, pcm, sampleRate) { const h = Buffer.alloc(44); h.write('RIFF', 0, 'ascii'); h.writeUInt32LE(36 + pcm.length, 4); h.write('WAVE', 8, 'ascii'); h.write('fmt ', 12, 'ascii'); h.writeUInt32LE(16, 16); // fmt chunk size h.writeUInt16LE(1, 20); // PCM h.writeUInt16LE(1, 22); // mono h.writeUInt32LE(sampleRate, 24); h.writeUInt32LE(sampleRate * 2, 28); // bytes per second h.writeUInt16LE(2, 32); // bytes per sample h.writeUInt16LE(16, 34); // bits per sample h.write('data', 36, 'ascii'); h.writeUInt32LE(pcm.length, 40); fs.writeFileSync(path, Buffer.concat([h, pcm]));}
// Read a 16-bit mono PCM WAV file. Returns { sampleRate, pcm }.export function readWav(path) { const b = fs.readFileSync(path); if (b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WAVE') { throw new Error(`${path} is not a WAV file`); } let format = null; let pcm = null; for (let off = 12; off + 8 <= b.length;) { const id = b.toString('ascii', off, off + 4); const size = b.readUInt32LE(off + 4); if (id === 'fmt ') { format = { codec: b.readUInt16LE(off + 8), channels: b.readUInt16LE(off + 10), sampleRate: b.readUInt32LE(off + 12), bits: b.readUInt16LE(off + 22), }; } else if (id === 'data') { pcm = b.subarray(off + 8, off + 8 + size); } off += 8 + size + (size & 1); } if (!format || !pcm || format.codec !== 1 || format.channels !== 1 || format.bits !== 16) { throw new Error(`${path} must be 16-bit mono PCM`); } return { sampleRate: format.sampleRate, pcm };}Python
Section titled “Python”streamaudio.py. It uses only the standard library. Python 3.13 removed the audioop module, so μ-law is done by hand.
# streamaudio.py: G.711 μ-law and WAV helpers for SIPRTC streams.import base64import structimport wave
def ulaw_to_pcm16(ulaw: bytes) -> bytes: """μ-law bytes -> 16-bit little-endian PCM.""" out = bytearray() for byte in ulaw: u = ~byte & 0xFF exponent = (u >> 4) & 0x07 mantissa = u & 0x0F magnitude = (((mantissa << 3) + 0x84) << exponent) - 0x84 out += struct.pack("<h", -magnitude if u & 0x80 else magnitude) return bytes(out)
def pcm16_to_ulaw(pcm: bytes) -> bytes: """16-bit little-endian PCM -> μ-law bytes.""" out = bytearray() for (s,) in struct.iter_unpack("<h", pcm[: len(pcm) // 2 * 2]): sign = 0x80 if s < 0 else 0 s = min(abs(s), 32635) + 0x84 exponent, mask = 7, 0x4000 while exponent > 0 and not s & mask: exponent -= 1 mask >>= 1 mantissa = (s >> (exponent + 3)) & 0x0F out.append(~(sign | (exponent << 4) | mantissa) & 0xFF) return bytes(out)
def payload_to_pcm16(payload: str, media_format: dict) -> bytes: """Decode a media payload to 16-bit PCM, whatever the stream's encoding.""" audio = base64.b64decode(payload) return ulaw_to_pcm16(audio) if media_format["encoding"] == "audio/x-mulaw" else audio
def pcm16_to_payload(pcm: bytes, media_format: dict) -> str: """Encode 16-bit PCM in the stream's encoding, as base64 for media.payload.""" audio = pcm16_to_ulaw(pcm) if media_format["encoding"] == "audio/x-mulaw" else pcm return base64.b64encode(audio).decode("ascii")
def write_wav(path: str, pcm: bytes, sample_rate: int) -> None: """Write 16-bit mono PCM to a WAV file.""" with wave.open(path, "wb") as w: w.setnchannels(1) w.setsampwidth(2) w.setframerate(sample_rate) w.writeframes(pcm)
def read_wav(path: str) -> tuple[int, bytes]: """Read a 16-bit mono PCM WAV file. Returns (sample_rate, pcm).""" with wave.open(path, "rb") as w: if w.getnchannels() != 1 or w.getsampwidth() != 2: raise ValueError(f"{path} must be 16-bit mono PCM") return w.getframerate(), w.readframes(w.getnframes())Example: record a call (one-way stream)
Section titled “Example: record a call (one-way stream)”This server saves each track of a one-way stream to a WAV file when the stream ends. Start it with TinyML like:
<Response> <Start> <Stream url="wss://stream.example.com/record?token=change-me" track="both_tracks"/> </Start> <Dial><Number>+15550100123</Number></Dial></Response>The server checks the token query parameter before it accepts audio. Run it behind a TLS-terminating proxy or load balancer so SIPRTC can reach it at a wss:// URL with a public certificate.
Node.js
Section titled “Node.js”Needs Node.js 18 or later and the ws package (npm install ws).
// record.mjs: saves each track of a one-way stream to a WAV file.// Use with <Start><Stream url="wss://your-host/record?token=..." track="both_tracks"/></Start>import { WebSocketServer } from 'ws';import { payloadToPcm16, writeWav } from './audio.mjs';
const TOKEN = process.env.STREAM_TOKEN || 'change-me';
const wss = new WebSocketServer({ port: Number(process.env.PORT || 8080), handleProtocols: (protocols) => (protocols.has('ws-protocol') ? 'ws-protocol' : false),});
wss.on('connection', (ws, req) => { const url = new URL(req.url, 'http://localhost'); if (url.searchParams.get('token') !== TOKEN) { ws.close(1008, 'bad token'); return; }
let start = null; // the start message const tracks = { inbound: [], outbound: [] }; // 16-bit PCM chunks per track
ws.on('message', (data, isBinary) => { if (isBinary) return; const msg = JSON.parse(data.toString()); switch (msg.event) { case 'start': start = msg; console.log(`stream ${msg.stream_sid} for call ${msg.start.call_sid}`, msg.start.media_format, msg.custom_parameters); break; case 'media': if (!start) return; // ignore audio before start tracks[msg.media.track]?.push(payloadToPcm16(msg.media.payload, start.start.media_format)); break; case 'dtmf': console.log('caller pressed', msg.dtmf.digit); break; case 'stop': console.log('stream stopped by SIPRTC'); break; } });
ws.on('close', () => { if (!start) return; const rate = start.start.media_format.sample_rate; for (const [track, chunks] of Object.entries(tracks)) { if (chunks.length === 0) continue; const file = `${start.stream_sid}-${track}.wav`; writeWav(file, Buffer.concat(chunks), rate); console.log('saved', file); } });});Python
Section titled “Python”Needs Python 3.10 or later and the websockets package, version 13 or later (pip install websockets).
# record.py: saves each track of a one-way stream to a WAV file.# Use with <Start><Stream url="wss://your-host/record?token=..." track="both_tracks"/></Start>import asyncioimport jsonimport osfrom urllib.parse import parse_qs, urlsplit
from websockets.asyncio.server import serve
from streamaudio import payload_to_pcm16, write_wav
TOKEN = os.environ.get("STREAM_TOKEN", "change-me")
async def handler(ws): query = parse_qs(urlsplit(ws.request.path).query) if query.get("token") != [TOKEN]: await ws.close(1008, "bad token") return
start = None # the start message tracks = {"inbound": [], "outbound": []} # 16-bit PCM chunks per track
async for message in ws: if isinstance(message, bytes): continue msg = json.loads(message) event = msg.get("event") if event == "start": start = msg print("stream", msg["stream_sid"], "for call", msg["start"]["call_sid"], msg["start"]["media_format"], msg.get("custom_parameters")) elif event == "media" and start: # ignore audio before start track = msg["media"]["track"] if track in tracks: tracks[track].append(payload_to_pcm16(msg["media"]["payload"], start["start"]["media_format"])) elif event == "dtmf": print("caller pressed", msg["dtmf"]["digit"]) elif event == "stop": print("stream stopped by SIPRTC")
# the connection is closed if start: rate = start["start"]["media_format"]["sample_rate"] for track, chunks in tracks.items(): if chunks: path = f"{start['stream_sid']}-{track}.wav" write_wav(path, b"".join(chunks), rate) print("saved", path)
async def main(): port = int(os.environ.get("PORT", "8080")) async with serve(handler, "0.0.0.0", port, subprotocols=["ws-protocol"]): await asyncio.get_running_loop().create_future() # run forever
if __name__ == "__main__": asyncio.run(main())Example: a two-way bot with barge-in
Section titled “Example: a two-way bot with barge-in”This server shows the main parts of a voice bot:
- When the stream starts, it plays
greeting.wavto the caller, followed by a mark namedgreeting. - It counts the mark’s echoes. The second echo means the greeting has finished playing.
- If the caller presses a key while the greeting is playing, it sends
clear, which stops the greeting at once (barge-in). The cleared mark is echoed straight away. - Once the greeting is over, it echoes the caller’s own voice back to them, which is an easy way to hear the round trip. The inbound payload is already in the stream’s format, so it is sent back unchanged.
A real bot would send the caller’s audio to a speech recogniser, send text-to-speech audio back, and send clear when the recogniser hears the caller start to speak.
Start it with TinyML like:
<Response> <Connect> <Stream url="wss://bot.example.com/bot?token=change-me">{"customer_id": "C-1042"}</Stream> </Connect></Response>greeting.wav must be 16-bit mono PCM at the rate the stream uses: 8000 Hz unless you ask for audio/L16 at 16000 Hz on a wideband call.
Node.js
Section titled “Node.js”// bot.mjs: a two-way stream server. It plays greeting.wav, then echoes// the caller back to them. A key press interrupts the greeting (barge-in).// Use with <Connect><Stream url="wss://your-host/bot?token=..."/></Connect>import { WebSocketServer } from 'ws';import { pcm16ToPayload, readWav } from './audio.mjs';
const TOKEN = process.env.STREAM_TOKEN || 'change-me';const GREETING = process.env.GREETING || 'greeting.wav';
const wss = new WebSocketServer({ port: Number(process.env.PORT || 8080), handleProtocols: (protocols) => (protocols.has('ws-protocol') ? 'ws-protocol' : false),});
function send(ws, msg) { ws.send(JSON.stringify(msg));}
// Queue 16-bit PCM for playback in 100 ms messages, then a mark.function play(ws, pcm, mediaFormat, markName) { const bytesPer100ms = mediaFormat.sample_rate / 10 * 2; // 16-bit samples for (let i = 0; i < pcm.length; i += bytesPer100ms) { send(ws, { event: 'media', media: { payload: pcm16ToPayload(pcm.subarray(i, i + bytesPer100ms), mediaFormat) } }); } send(ws, { event: 'mark', mark: { name: markName } });}
wss.on('connection', (ws, req) => { const url = new URL(req.url, 'http://localhost'); if (url.searchParams.get('token') !== TOKEN) { ws.close(1008, 'bad token'); return; }
let mediaFormat = null; let greeting = 'none'; // none | playing | done const markEchoes = new Map(); // SIPRTC echoes each mark twice
ws.on('message', (data, isBinary) => { if (isBinary) return; const msg = JSON.parse(data.toString()); switch (msg.event) { case 'start': { mediaFormat = msg.start.media_format; console.log(`call ${msg.start.call_sid}`, mediaFormat, msg.custom_parameters); const wav = readWav(GREETING); if (wav.sampleRate !== mediaFormat.sample_rate) { console.error(`${GREETING} is ${wav.sampleRate} Hz but the stream is ${mediaFormat.sample_rate} Hz`); greeting = 'done'; break; } greeting = 'playing'; play(ws, wav.pcm, mediaFormat, 'greeting'); break; } case 'media': // Echo the caller once the greeting is over. The payload is already // in the stream's encoding and rate, so it can go straight back. if (greeting === 'done' && msg.media.track === 'inbound') { send(ws, { event: 'media', media: { payload: msg.media.payload } }); } break; case 'mark': { const n = (markEchoes.get(msg.mark.name) || 0) + 1; markEchoes.set(msg.mark.name, n); // first echo: mark received; second echo: playback reached it (or it was cleared) if (n === 2 && msg.mark.name === 'greeting') { greeting = 'done'; console.log('greeting finished, echoing the caller'); } break; } case 'dtmf': console.log('caller pressed', msg.dtmf.digit); if (greeting === 'playing') send(ws, { event: 'clear' }); // barge-in break; case 'stop': console.log('call over'); break; } });});Python
Section titled “Python”# bot.py: a two-way stream server. It plays greeting.wav, then echoes# the caller back to them. A key press interrupts the greeting (barge-in).# Use with <Connect><Stream url="wss://your-host/bot?token=..."/></Connect>import asyncioimport jsonimport osfrom collections import Counterfrom urllib.parse import parse_qs, urlsplit
from websockets.asyncio.server import serve
from streamaudio import pcm16_to_payload, read_wav
TOKEN = os.environ.get("STREAM_TOKEN", "change-me")GREETING = os.environ.get("GREETING", "greeting.wav")
async def send(ws, msg): await ws.send(json.dumps(msg))
async def play(ws, pcm, media_format, mark_name): """Queue 16-bit PCM for playback in 100 ms messages, then a mark.""" step = media_format["sample_rate"] // 10 * 2 # bytes of 16-bit PCM per 100 ms for i in range(0, len(pcm), step): payload = pcm16_to_payload(pcm[i:i + step], media_format) await send(ws, {"event": "media", "media": {"payload": payload}}) await send(ws, {"event": "mark", "mark": {"name": mark_name}})
async def handler(ws): query = parse_qs(urlsplit(ws.request.path).query) if query.get("token") != [TOKEN]: await ws.close(1008, "bad token") return
greeting = "none" # none | playing | done mark_echoes = Counter() # SIPRTC echoes each mark twice
async for message in ws: if isinstance(message, bytes): continue msg = json.loads(message) event = msg.get("event")
if event == "start": media_format = msg["start"]["media_format"] print("call", msg["start"]["call_sid"], media_format, msg.get("custom_parameters")) rate, pcm = read_wav(GREETING) if rate != media_format["sample_rate"]: print(f"{GREETING} is {rate} Hz but the stream is {media_format['sample_rate']} Hz") greeting = "done" continue greeting = "playing" await play(ws, pcm, media_format, "greeting")
elif event == "media": # Echo the caller once the greeting is over. The payload is already # in the stream's encoding and rate, so it can go straight back. if greeting == "done" and msg["media"]["track"] == "inbound": await send(ws, {"event": "media", "media": {"payload": msg["media"]["payload"]}})
elif event == "mark": name = msg["mark"]["name"] mark_echoes[name] += 1 # first echo: mark received; second echo: playback reached it (or it was cleared) if mark_echoes[name] == 2 and name == "greeting": greeting = "done" print("greeting finished, echoing the caller")
elif event == "dtmf": print("caller pressed", msg["dtmf"]["digit"]) if greeting == "playing": await send(ws, {"event": "clear"}) # barge-in
elif event == "stop": print("call over")
async def main(): port = int(os.environ.get("PORT", "8080")) async with serve(handler, "0.0.0.0", port, subprotocols=["ws-protocol"]): await asyncio.get_running_loop().create_future() # run forever
if __name__ == "__main__": asyncio.run(main())Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause |
|---|---|
| Loud noise instead of speech | Decoding μ-law as PCM or the other way round, or the wrong byte order for L16. Check start.media_format.encoding. |
| Speech too fast or too slow, or high or low pitched | Wrong sample rate. Use start.media_format.sample_rate for both decoding and the audio you send. |
| Your audio isn’t heard | It’s a one-way stream (<Start>), the messages are binary frames instead of text, media.track is set to inbound, or the clip is shorter than about 100 ms and nothing follows it. |
| The bot’s audio is cut off | You sent clear, or queued more than 30 seconds of audio. |
| The connection never opens | The URL breaks the URL rules, the certificate is not publicly trusted, or your server didn’t accept the ws-protocol subprotocol. Check the stream-error callback. |