Real-time streaming
Browser microphone streaming
Stream from the microphone with an AudioWorklet and a temporary token.
How it fits together
Your page asks your backend for a token
After checking your own user session.
Your backend calls POST /v1/auth/grant
With an API key that has the stream scope, and returns the sht_ token.
The browser streams the microphone
To wss://api.shihab.co.uk/v1/listen/stream?token=sht_...
Mint a token on your server
curl https://api.shihab.co.uk/v1/auth/grant \
-H "Authorization: Bearer $SHIHAB_API_KEY" \
-H "Content-Type: application/json" \
-d '{"ttl_seconds": 60}'With the JavaScript SDK
startMicrophoneStream asks for the microphone, captures audio with an AudioWorklet, converts it to 16 kHz 16-bit PCM and sends 100 ms chunks.
import { startMicrophoneStream } from '@shihab/asr/browser';
const { token } = await (await fetch('/shihab-token', { method: 'POST' })).json();
const mic = await startMicrophoneStream({
token,
onTranscript: (text, event) => {
if (event.is_final) {
finalText.textContent += text + ' ';
liveText.textContent = '';
} else {
liveText.textContent = text;
}
},
onError: (err) => console.error(err),
});
stopButton.onclick = async () => {
const finished = await mic.stop(); // { audio_seconds, billed_seconds, cost_usd }
console.log(finished);
};Without a bundler, import the same helper from https://voice.shihab.co.uk/sdk/shihab-asr-browser-1.1.0.js.
Without an SDK: AudioWorklet
The worklet runs on the audio thread and hands raw samples to the page, which converts them to 16-bit PCM and sends them as binary frames.
// public/pcm-worklet.js: hands each 128-sample frame of mono audio to the page
class PcmCapture extends AudioWorkletProcessor {
process(inputs) {
const channel = inputs[0]?.[0];
if (channel) this.port.postMessage(channel.slice(0));
return true;
}
}
registerProcessor('pcm-capture', PcmCapture);const { token } = await (await fetch('/shihab-token', { method: 'POST' })).json();
// Ask the browser for 16 kHz so no resampling is needed
const ctx = new AudioContext({ sampleRate: 16000 });
await ctx.audioWorklet.addModule('/pcm-worklet.js');
const media = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
});
const source = ctx.createMediaStreamSource(media);
const capture = new AudioWorkletNode(ctx, 'pcm-capture');
source.connect(capture);
const params = new URLSearchParams({ encoding: 'linear16', sample_rate: String(ctx.sampleRate), token });
const ws = new WebSocket(`wss://api.shihab.co.uk/v1/listen/stream?${params}`);
// Batch 128-sample frames into 100 ms chunks of 16-bit PCM
const chunkSamples = ctx.sampleRate / 10;
let pending = new Int16Array(chunkSamples);
let filled = 0;
capture.port.onmessage = ({ data }) => {
for (let i = 0; i < data.length; i++) {
const s = Math.max(-1, Math.min(1, data[i]));
pending[filled++] = s < 0 ? s * 0x8000 : s * 0x7fff;
if (filled === chunkSamples) {
if (ws.readyState === WebSocket.OPEN) ws.send(pending.buffer);
pending = new Int16Array(chunkSamples);
filled = 0;
}
}
};
ws.onmessage = ({ data }) => {
const msg = JSON.parse(data);
if (msg.type === 'Results') {
if (msg.is_final) finalText.textContent += msg.transcript + ' ';
liveText.textContent = msg.is_final ? '' : msg.transcript;
} else if (msg.type === 'Error') {
console.error(msg.code, msg.message);
}
};
async function stop() {
ws.send(JSON.stringify({ type: 'CloseStream' })); // the server answers with Finished, then closes
media.getTracks().forEach((t) => t.stop());
await ctx.close();
}Alternative: MediaRecorder and Opus
If you already record with MediaRecorder, stream its chunks with encoding=opus. PCM through an AudioWorklet gives the lowest latency; Opus uses less bandwidth.
const params = new URLSearchParams({ encoding: 'opus', token });
const ws = new WebSocket(`wss://api.shihab.co.uk/v1/listen/stream?${params}`);
const media = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(media, { mimeType: 'audio/webm;codecs=opus' });
recorder.ondataavailable = (e) => {
if (e.data.size > 0 && ws.readyState === WebSocket.OPEN) ws.send(e.data);
};
ws.onopen = () => recorder.start(250); // a chunk every 250 ms
ws.onmessage = ({ data }) => console.log(JSON.parse(data));
// stop: recorder.stop(); then ws.send(JSON.stringify({ type: 'CloseStream' }))Need help? Email [email protected] or message us on WhatsApp.