Real-time streaming
Real-time streaming
Stream audio over WebSocket and receive interim and final transcripts.
WSSwss://api.shihab.co.uk/v1/listen/stream
Connect
Open a WebSocket, send audio as binary frames, and read JSON text messages back. Authenticate with an Authorization: Bearer header from a server, or with ?token=sht_... from a browser (see Authentication). Send 20 to 250 ms of audio per frame, as it is captured.
URL
wss://api.shihab.co.uk/v1/listen/stream?encoding=linear16&sample_rate=16000&interim_results=true&endpointing=800Query parameters
modelstringOptionalDefault:shihab-asr-v1The model: shihab-asr-v1, the only one (you can leave it out).languagestringOptionalDefault:arar, orar-XXfor any Arab country (ar-PS,ar-EG,ar-MA...).encoding"linear16" | "mulaw" | "alaw" | "opus"OptionalDefault:linear16linear16: 16-bit little-endian PCM.mulaw,alaw: telephony (usually 8 kHz).opus: Ogg or WebM container from a browser MediaRecorder.sample_rateintegerOptionalDefault:160008000 to 48000. Ignored for opus.channelsintegerOptionalDefault:11, or 2 to have us downmix interleaved stereo.interim_resultsbooleanOptionalDefault:trueSend partial transcripts while someone is still speaking.endpointinginteger (ms)OptionalDefault:800300 to 3000. Milliseconds of silence that end an utterance (speech_final). Lower is snappier for voice agents; higher suits dictation.vad_eventsbooleanOptionalDefault:falseSend SpeechStarted when speech begins.numeralsbooleanOptionalDefault:falseDigits instead of number words.tagstring (repeatable)OptionalUp to 5 tags for your logs.tokenstringOptionalA temporary token (sht_...) for browsers, instead of a header.
Client messages
| Message | What it does |
|---|---|
| Binary frame | Audio in the encoding you declared. |
| {"type":"KeepAlive"} | Keeps the stream open while you have no audio to send (send one every few seconds). |
| {"type":"Finalize"} | Flushes the current utterance as a final result now, without waiting for silence. |
| {"type":"CloseStream"} | No more audio. We send the remaining results, then Finished, then close with 1000. |
Server messages
Messages, one per line
{"type":"Metadata","request_id":"req_01JA...","model":"shihab-asr-v1","model_version":"1.1.0","created":"2026-10-12T12:00:00Z"}
{"type":"SpeechStarted","timestamp":3.12}
{"type":"Results","is_final":false,"speech_final":false,"start":3.1,"duration":1.4,"transcript":"مرحبا بدي"}
{"type":"Results","is_final":true,"speech_final":true,"start":3.1,"duration":2.9,"transcript":"مرحبا، بدي أسأل عن طلبيتي."}
{"type":"UtteranceEnd","last_word_end":6.0}
{"type":"Finished","request_id":"req_01JA...","audio_seconds":61.2,"billed_seconds":62,"cost_usd":"0.0186"}| Type | Meaning |
|---|---|
| Metadata | First message: the request_id and model of this stream. |
| SpeechStarted | Speech began at timestamp seconds (only with vad_events=true). |
| Results | A transcript for the audio from start for duration seconds. is_final: false is interim and will be replaced; is_final: true will not change. speech_final: true also marks the end of an utterance (endpointing). |
| UtteranceEnd | Silence after the last word, which ended at last_word_end seconds. |
| Error | A problem, with code and message. When the server ends the stream, Finished (billing so far) follows, then the close code. |
| Finished | Last message on every close: audio_seconds, billed_seconds and cost_usd for the stream. |
Close codes
| Code | Meaning |
|---|---|
| 1000 | Normal close after CloseStream (or by you). |
| 1011 | Server error. Reconnect with backoff. |
| 4001 | Authentication failed: missing, invalid or expired key or token. |
| 4002 | Out of credit (an Error message with insufficient_credits comes first). |
| 4008 | Idle: no audio and no KeepAlive for 15 seconds. |
| 4013 | Stream longer than 3 hours. |
| 4029 | Too many concurrent streams or requests. |
| 4400 | Invalid query parameters. |
Node.js example
With the SDK (chunks sent before the socket opens are queued for you):
Node.js
import fs from 'node:fs';
import { ShihabASR } from '@shihab/asr';
const client = new ShihabASR({ apiKey: process.env.SHIHAB_API_KEY });
const stream = client.stream({ encoding: 'linear16', sampleRate: 16000, interimResults: true });
stream.on('results', (e) => console.log(e.is_final ? 'final ' : 'interim', e.transcript));
stream.on('utteranceEnd', (e) => console.log('-- pause at', e.last_word_end));
stream.on('error', (err) => console.error(err.code, err.message));
// 16 kHz, 16-bit mono PCM in 100 ms chunks (3,200 bytes), paced like live audio
for await (const chunk of fs.createReadStream('call.pcm', { highWaterMark: 3200 })) {
stream.send(chunk);
await new Promise((r) => setTimeout(r, 100));
}
const finished = await stream.close(); // sends CloseStream, waits for the last results
console.log(finished.audio_seconds, finished.billed_seconds, finished.cost_usd);Or speak the protocol directly:
Node.js (ws)
// npm install ws
import fs from 'node:fs';
import WebSocket from 'ws';
const url = 'wss://api.shihab.co.uk/v1/listen/stream?encoding=linear16&sample_rate=16000&interim_results=true';
const ws = new WebSocket(url, { headers: { Authorization: `Bearer ${process.env.SHIHAB_API_KEY}` } });
ws.on('open', async () => {
const pcm = fs.readFileSync('call.pcm'); // 16 kHz, 16-bit mono PCM
for (let i = 0; i < pcm.length; i += 3200) {
ws.send(pcm.subarray(i, i + 3200)); // 100 ms per frame
await new Promise((r) => setTimeout(r, 100));
}
ws.send(JSON.stringify({ type: 'CloseStream' }));
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
const msg = JSON.parse(data.toString());
if (msg.type === 'Results') console.log(msg.is_final ? 'final ' : 'interim', msg.transcript);
else if (msg.type === 'Finished') console.log('billed seconds:', msg.billed_seconds);
else if (msg.type === 'Error') console.error(msg.code, msg.message);
});
ws.on('close', (code) => console.log('closed with', code));Python example
Python
import asyncio
import wave
from shihab_asr import AsyncShihabASR
async def main(path: str) -> None:
with wave.open(path, "rb") as w: # 16-bit PCM WAV
rate, channels, pcm = w.getframerate(), w.getnchannels(), w.readframes(w.getnframes())
chunk = rate * channels * 2 // 10 # 100 ms
async with AsyncShihabASR() as client:
async with client.stream(sample_rate=rate, channels=channels, interim_results=True) as s:
async def feed() -> None:
for i in range(0, len(pcm), chunk):
await s.send(pcm[i : i + chunk])
await asyncio.sleep(0.1) # real-time pacing
await s.close()
task = asyncio.create_task(feed())
async for event in s:
if event.type == "Results" and event.is_final:
print(f"[{event.start:6.2f}s] {event.transcript}")
await task
print(f"billed {s.finished.billed_seconds} s, ${s.finished.cost_usd}")
asyncio.run(main("call.wav"))Python (websockets)
# pip install "websockets>=13"
import asyncio
import json
import os
from websockets.asyncio.client import connect
URL = "wss://api.shihab.co.uk/v1/listen/stream?encoding=linear16&sample_rate=16000"
async def main() -> None:
headers = {"Authorization": f"Bearer {os.environ['SHIHAB_API_KEY']}"}
async with connect(URL, additional_headers=headers) as ws:
async def send_audio() -> None:
with open("call.pcm", "rb") as f: # 16 kHz, 16-bit mono PCM
while chunk := f.read(3200): # 100 ms
await ws.send(chunk)
await asyncio.sleep(0.1)
await ws.send(json.dumps({"type": "CloseStream"}))
sender = asyncio.create_task(send_audio())
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "Results":
print("final " if msg["is_final"] else "interim", msg["transcript"])
elif msg["type"] == "Finished":
print("billed seconds:", msg["billed_seconds"])
elif msg["type"] == "Error":
print("error:", msg["code"], msg["message"])
await sender
asyncio.run(main())Billing and limits
- Streams are billed on the seconds of audio we receive, not on how long the socket stays open: $0.018 per minute, metered in 10-second ticks and settled on close. The Finished message has the exact numbers.
- When your balance reaches zero the stream receives
Error insufficient_creditsand closes with4002. - Default concurrency is 2 streams per organisation (rate limits); a stream lasts at most 3 hours.
Need help? Email [email protected] or message us on WhatsApp.