Streaming from a browser or app
Optional. Keep your API key off the client by connecting browsers and mobile apps with single-use tokens.
Only for client-side streaming
Servers stream with the API key directly, exactly like every other endpoint (see Live transcription). Use tokens only when audio leaves from a browser or mobile app, where a wv_sk_ key would be exposed.
Browsers can't set an Authorization header on a WebSocket, and anything shipped in an app can be extracted. So the client never holds your key:
- Your server uses the API key to mint a short-lived, single-use token with
POST /v1/stt/stream/tokens. - The client connects to
wss://api.voice.wistfare.com/v1/stt/stream?token=wv_st_…and streams audio. Your server isn't in the audio path.
1. Mint a token on your server
Add an endpoint that checks your user is signed in, then asks Wistfare for a token:
# FastAPI endpoint your web page calls before it starts recording.
from fastapi import FastAPI
from wistfareai import WistfareAI
app = FastAPI()
client = WistfareAI() # reads WISTFARE_API_KEY on your server
@app.post("/api/stt-token")
def stt_token():
# Check that the caller is one of your signed-in users before minting a token.
token = client.speech_to_text.stream_tokens.create(
model="wistfare-stt-v3-beta", language="auto", latency="balanced", expires_in=60
)
return {"token": token.token, "expires_at": token.expires_at.isoformat()}The API answers 201 Created:
{
"token": "wv_st_Vb3kQ9xZ2mN7pR4tW8yC1dF6gH0jK5lA3sE9uI2o",
"expires_at": "2026-10-11T09:42:12Z",
"model": "wistfare-stt-v3-beta",
"language": "auto",
"latency": "balanced"
}How tokens behave:
- Single use. A token opens one socket. It's used up by the first connection attempt, even one that's refused.
- Short-lived. Connect before
expires_at.expires_inis 10 to 600 seconds (default 60). Once connected, the session can run its full 15 minutes. - Bound to its options.
model,languageandlatencycome from the token. Repeating them in the URL is fine, but a different value is refused withtoken_mismatch.boostandpunctuationcan still be added to the URL. - Billed like the key. The session bills the project of the key that minted the token, at the same rate.
Mint one token per recording, just before the client connects, and keep expires_in short. Each account can mint 20 tokens per minute by default (raisable on request), and the sessions they open count toward the account's concurrent live sessions.
2. Stream the microphone from the browser
With the JavaScript SDK, the browser connects with the token (no API key), captures the microphone with Web Audio, and hands float samples to sendFloat32, which resamples them to 24 kHz 16-bit and sends them:
import { WistfareAI } from 'wistfareai';
// Runs in the audio thread: forwards about 100 ms of microphone samples at a time.
const TAP = `registerProcessor('mic-tap', class extends AudioWorkletProcessor {
buf = new Float32Array(Math.round(sampleRate / 10));
n = 0;
process([input]) {
for (const sample of input[0] ?? []) {
this.buf[this.n++] = sample;
if (this.n === this.buf.length) {
this.port.postMessage(this.buf);
this.buf = new Float32Array(this.buf.length);
this.n = 0;
}
}
return true;
}
});`;
/** Call from a click handler (browsers only start audio after a user gesture). */
export async function startLiveTranscription({ onText }) {
const ctx = new AudioContext(); // created inside the gesture so it may start
// A single-use token from your server (step 1). Model, language and latency come from it.
const { token } = await fetch('/api/stt-token', { method: 'POST' }).then((r) => r.json());
const stream = await new WistfareAI().speechToText.realtime.connect({ token });
let committed = '';
stream.on('final', (e) => {
committed = e.replace ? e.text : `${committed} ${e.text}`.trim();
onText(committed, '');
});
stream.on('partial', (e) => onText(committed, e.text));
const mic = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
});
await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([TAP], { type: 'text/javascript' })));
await ctx.resume();
const tap = new AudioWorkletNode(ctx, 'mic-tap');
ctx.createMediaStreamSource(mic).connect(tap);
tap.connect(ctx.destination); // keeps the graph running; the node outputs silence
tap.port.onmessage = ({ data }) => stream.sendFloat32(data, ctx.sampleRate);
return {
/** Stop recording and resolve with the complete transcript. */
async stop() {
tap.port.onmessage = null;
mic.getTracks().forEach((track) => track.stop());
await ctx.close();
return stream.end(); // { text, words, segments, transcriptionId, costCents, … }
},
};
}Wire it to a page:
<button id="start">Start</button>
<button id="stop" disabled>Stop</button>
<p id="transcript"></p>
<script type="module">
import { startLiveTranscription } from './live-transcription.js';
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const out = document.getElementById('transcript');
let session;
startButton.onclick = async () => {
startButton.disabled = true;
session = await startLiveTranscription({
onText: (text, partial) => (out.textContent = `${text} ${partial}`),
});
stopButton.disabled = false;
};
stopButton.onclick = async () => {
stopButton.disabled = true;
out.textContent = (await session.stop()).text;
};
</script>An unknown, expired or already-used token makes connect() reject with AuthenticationError.
Without the SDK
The same flow with no dependencies: an AudioWorklet resamples to 24 kHz 16-bit in the audio thread and the page speaks the WebSocket protocol directly.
// Runs in the audio thread: resample to 24 kHz, convert to 16-bit, emit 320 ms chunks.
const WORKLET = `
class Pcm24k extends AudioWorkletProcessor {
constructor() {
super();
this.step = sampleRate / 24000; // input samples per output sample (48 kHz -> 2)
this.pos = 0; // read position within the current block
this.last = 0; // final sample of the previous block
this.buf = new Int16Array(7680); // 320 ms at 24 kHz
this.n = 0;
this.port.onmessage = () => { // "flush": hand over the partial chunk
this.port.postMessage({ flush: this.buf.slice(0, this.n).buffer });
this.n = 0;
};
}
process(inputs) {
const x = inputs[0][0]; // first channel: the model wants mono
if (!x) return true;
while (this.pos < x.length - 1) {
const i = Math.floor(this.pos);
const a = i < 0 ? this.last : x[i];
const s = a + (x[i + 1] - a) * (this.pos - i); // linear interpolation
this.buf[this.n++] = Math.max(-1, Math.min(1, s)) * 32767;
if (this.n === this.buf.length) {
this.port.postMessage(this.buf.buffer, [this.buf.buffer]);
this.buf = new Int16Array(7680);
this.n = 0;
}
this.pos += this.step;
}
this.pos -= x.length;
this.last = x[x.length - 1];
return true;
}
}
registerProcessor('pcm-24k', Pcm24k);
`;
/**
* Start transcribing the microphone. Call it from a click handler (browsers only start
* audio after a user gesture). Returns { stop }; stop() asks for the final transcript.
*/
export async function startLiveTranscription({ onText, onFinal, onError }) {
const ctx = new AudioContext(); // created inside the gesture so it may start
// 1. A single-use token from your server (step 1 above).
const res = await fetch('/api/stt-token', { method: 'POST' });
if (!res.ok) throw new Error('Could not get a transcription token');
const { token } = await res.json();
// 2. Microphone -> AudioWorklet -> 24 kHz 16-bit mono chunks.
const mic = await navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true },
});
const workletUrl = URL.createObjectURL(new Blob([WORKLET], { type: 'text/javascript' }));
await ctx.audioWorklet.addModule(workletUrl);
await ctx.resume();
const encoder = new AudioWorkletNode(ctx, 'pcm-24k');
ctx.createMediaStreamSource(mic).connect(encoder);
encoder.connect(ctx.destination); // keeps the graph running; the node outputs silence
// 3. The socket. Chunks captured before "ready" are queued, not dropped.
const ws = new WebSocket(
`wss://api.voice.wistfare.com/v1/stt/stream?token=${encodeURIComponent(token)}`,
);
const queue = [];
let ready = false;
const send = (data) => {
if (ready && ws.readyState === WebSocket.OPEN) ws.send(data);
else queue.push(data);
};
let words = [];
ws.onmessage = ({ data }) => {
const msg = JSON.parse(data);
if (msg.type === 'ready') {
ready = true;
for (const item of queue.splice(0)) ws.send(item);
} else if (msg.type === 'words') {
const fresh = msg.final.map((w) => w.word);
words = msg.replace ? fresh : words.concat(fresh);
onText(words.join(' '), msg.partial, msg.language);
} else if (msg.type === 'final') {
onFinal(msg);
} else if (msg.type === 'error') {
onError(msg);
}
};
ws.onclose = (event) => {
if (event.code >= 4000) onError({ code: event.code, message: 'Connection refused' });
mic.getTracks().forEach((track) => track.stop());
if (ctx.state !== 'closed') ctx.close();
};
encoder.port.onmessage = ({ data }) => {
if (data instanceof ArrayBuffer) return send(data); // a full 320 ms chunk
send(data.flush); // the last partial chunk…
send(JSON.stringify({ type: 'end' })); // …then ask for the final transcript
mic.getTracks().forEach((track) => track.stop());
};
return { stop: () => encoder.port.postMessage('flush') };
}Call startLiveTranscription({ onText, onFinal, onError }) from a click handler. Its stop() sends the last audio and the end message; onFinal then receives the complete transcript.
The messages (ready, words, final, error) are the same as for any live session; see the realtime protocol reference.
Browser notes
getUserMedia needs a secure context: HTTPS, or http://localhost while developing. Both versions resample from whatever rate the device runs at (usually 48 kHz), so they work in Chrome, Edge, Firefox and Safari. ScriptProcessorNode also works but is deprecated and runs on the main thread, so prefer AudioWorklet.
Mobile apps
The same pattern applies to iOS and Android: fetch a token from your backend, open the WebSocket with ?token=…, and send 16-bit mono 24 kHz PCM from the platform's audio capture API (for example AVAudioEngine with an AVAudioConverter, or Android's AudioRecord at 24,000 Hz with ENCODING_PCM_16BIT).