KhasbhaSTT LIVE
Transcribe live audio while people speak, over a WebSocket, from your server or a browser
KhasbhaSTT LIVE writes down speech while it's being spoken. You stream raw audio to a WebSocket, and the text comes back as people talk: a partial transcript that firms up as the words come, then a final one each time the speaker pauses. Use it for live captions, dictation, voice search, or calls you want to read as they happen.
For a recording you already have, use KhasbhaSTT instead: it costs less, takes the file as it is, and hears the whole recording before it writes.
You'll need an API key and some API credit: see Get Your API Key. KhasbhaSTT LIVE costs 5 DA a minute of audio, billed per second, with a minimum of 15 seconds per session. To try it with your microphone first, open Speech to text in the Developer workspace.
How a session works
Your server asks for a token
POST /stt/live/token, called with your API key, returns a single-use token and the socket's url. The session's settings go in this request: the language, the dialect, a vocabulary of names to recognize, and maxSeconds, the longest it may last. The token opens one session, within two minutes.
Open the socket
Open url from your server, or hand it to a browser or an app. Voice213 checks your account and your API credit, then sends a ready message.
Stream audio
Send 16-bit PCM audio, mono, at 16 kHz, in binary frames of 20 to 100 ms, at the pace it's recorded. Keep streaming during silence: the end of a sentence is heard in the silence after it.
Read the transcript
transcript messages arrive while people speak. A partial one replaces the one before it. A final one closes the sentence: add it to your transcript.
End the session
Send {"type": "end"}. The last final transcripts arrive, then an ended message with the seconds billed and the cost, and the socket closes.
The token keeps your API key on your server: it's the only thing a browser or an app ever sees, it opens a single session, and it can be tied to your website. See the Live Transcription Socket reference for every message.
From your server
The SDKs take care of each step: connect() creates the token and opens the socket, sendFile() (send_file() in Python) streams a recording, and the transcript arrives as events. Both examples stream call.wav at real-time pace, print each sentence as it's finalized, and end the session when the file is done. sendFile() reads a WAV file at any sample rate and sends it as 16 kHz mono; convert other formats, such as MP3, to WAV first with ffmpeg:
ffmpeg -i call.mp3 -ar 16000 -ac 1 -c:a pcm_s16le call.wavimport asyncio
from voice213 import AsyncVoice213
async def main():
client = AsyncVoice213() # reads VOICE213_API_KEY; live sessions are async
async with client.speech_to_text.live.connect(
language="ar", dialect="algerian", vocabulary=["Yalidine", "Baridimob"]
) as session:
# Streams the file at real-time pace, then ends the session and returns its summary
sender = asyncio.create_task(session.send_file("call.wav"))
async for event in session:
if event.type == "transcript" and event.final:
print(event.text)
summary = await sender # raises a LiveSessionError if the session failed
print(f"{summary.reason}: {summary.billable_seconds} s billed, {summary.cost} DA")
asyncio.run(main())import Voice213 from "@voice213/sdk";
const voice213 = new Voice213(); // reads VOICE213_API_KEY
const session = await voice213.speechToText.live.connect({
language: "ar",
dialect: "algerian",
vocabulary: ["Yalidine", "Baridimob"],
});
session.on("transcript", ({ text, final }) => final && console.log(text));
// Streams the file at real-time pace, then ends the session and returns its summary
// (it rejects with a LiveSessionError if the session failed)
const summary = await session.sendFile("call.wav");
console.log(`${summary.reason}: ${summary.billableSeconds} s billed, ${summary.cost} DA`);Node.js 21 and older have no built-in WebSocket: npm install ws, and pass it to the client with new Voice213({ WebSocket }).
To stream audio as it's captured, such as a call in progress, send 16 kHz, 16-bit mono PCM with session.send(), at the pace it's recorded, and finish with session.end(), which returns the summary. A client that gets more than 10 seconds ahead of real time is stopped with TOO_FAST; sendFile() keeps the pace for you. See JavaScript & TypeScript and Python for everything a session does.
From a browser
Never put your API key in a web page. Your server creates the token instead, for your page's origin, and hands the page only the socket's url. The page then streams the microphone straight to Voice213, so the audio doesn't pass through your server. It takes two pieces:
- A route on your server that creates the token.
- The page, which opens the session with
LiveSessionfrom the JavaScript SDK, streams the microphone and shows the text. The SDK captures the microphone as 16 kHz, 16-bit frames in an audio worklet it carries.
Browsers only open the microphone on secure pages (HTTPS, or localhost while you develop), after the visitor allows it, and from a click.
1. The token route
Your server asks for the token with your API key and with origin, the origin of the page that will open the socket. A token created with an origin only opens a socket from a page on that origin, so other websites can't use it. maxSeconds caps each session, here at 10 minutes, or 50 DA.
// npm install express @voice213/sdk
import express from "express";
import Voice213, { APIError } from "@voice213/sdk";
const app = express();
app.use(express.static("public"));
const voice213 = new Voice213(); // reads VOICE213_API_KEY
// The page that opens the socket. While you develop: http://localhost:8080
const SITE_ORIGIN = "https://shop.example";
app.post("/api/live-token", async (req, res) => {
// Check here that the visitor is one of your signed-in users: each token can spend your API credit
try {
const token = await voice213.speechToText.live.createToken({
language: "ar",
dialect: "algerian",
maxSeconds: 600,
origin: SITE_ORIGIN,
});
res.json({ url: token.url });
} catch (error) {
res.status(error instanceof APIError ? error.status : 502).json({ error: error.message });
}
});
app.listen(8080);In Python, the same route calls client.speech_to_text.live.create_token(...): see Create a Live Token for a FastAPI version.
2. The page
The click asks your server for a token and starts the microphone at the same time: LiveSession takes the promise of the url, and opens the socket as soon as it arrives. Until then, it keeps the last 5 seconds of audio and sends them first, and audio sent before ready waits on the server, up to 5 seconds of it, so the first words aren't lost while the session starts.
<button id="start">Start</button>
<button id="stop" disabled>Stop</button>
<p id="transcript" dir="auto" style="white-space: pre-line"></p>
<p id="partial" dir="auto" style="opacity: 0.6"></p>
<script type="module">
import { LiveSession } from "https://cdn.jsdelivr.net/npm/@voice213/sdk@0.1.0/+esm";
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const transcript = document.getElementById("transcript");
const partial = document.getElementById("partial");
startButton.onclick = async () => {
startButton.disabled = true;
transcript.textContent = "";
// The socket's url from your server, still on its way while the microphone starts
const url = fetch("/api/live-token", { method: "POST" }).then((response) => {
if (!response.ok) throw new Error(`No live token (${response.status})`);
return response.json().then((token) => token.url);
});
const session = new LiveSession(url);
session.on("transcript", () => {
transcript.textContent = session.text; // the final sentences, one per line
partial.textContent = session.partial; // the sentence being spoken
});
// The summary once the session is over and billed, or why it failed
session.finished
.then(({ billableSeconds, cost }) => (partial.textContent = `${billableSeconds} s billed, ${cost} DA`))
.catch((error) => {
if (error.code !== "CLOSED") partial.textContent = error.message;
})
.finally(() => {
stopButton.disabled = true;
startButton.disabled = false;
});
// Stop turns the microphone off at once: the last words arrive, then the summary
stopButton.onclick = () => {
stopButton.disabled = true;
session.end();
};
try {
// In the click: browsers only start audio from a user gesture
await session.startMicrophone();
stopButton.disabled = false;
} catch (error) {
// No microphone (refused or missing), or the session failed while it started
if (session.status !== "failed") {
partial.textContent = error.code === "MIC_DENIED" ? "Allow the microphone, then try again." : error.message;
}
session.close();
}
};
</script>- The page imports the SDK from a CDN, pinned to a version. With a bundler,
npm install @voice213/sdkandimport { LiveSession } from "@voice213/sdk"instead. startMicrophone()brings the microphone down to 16 kHz in an audio worklet, with an anti-aliasing filter, and streams it in frames of 40 ms. It returns aMicrophone, withlevel(0 to 1) for a meter,mutedto send silence, andstop().end()andclose()stop it too.- The worklet loads from a
blob:URL. If your site's Content-Security-Policy blocksblob:scripts, serve the file@voice213/sdk/microphone-worklet.js(innode_modules/@voice213/sdk/dist/) from your site, and pass its address:session.startMicrophone({ workletUrl: "/microphone-worklet.js" }).
See Live transcription in a browser for every option, and the browser example in the reference for a module that handles every message.
Partial and final transcripts
Each sentence is a segment, numbered from 0. While it's spoken, you get partial transcripts of it, and when the speaker pauses, its final transcript:
{ "type": "transcript", "segment": 0, "text": "السلام عليكم", "final": false }
{ "type": "transcript", "segment": 0, "text": "السلام عليكم راني نعيط على", "final": false }
{ "type": "transcript", "segment": 0, "text": "السلام عليكم، راني نعيط على la commande تاعي.", "final": true }
{ "type": "transcript", "segment": 1, "text": "وصلتني", "final": false }- A partial replaces the previous partial of its segment. Show it while it changes, greyed out for example.
- A final is appended. It's the segment's finished text: add it to your transcript and drop the segment's partial. The next sentence gets the next number.
- A short sentence can come as a final straight away, without partials.
- To finalize a sentence without waiting for the silence after it, for example when a push-to-talk button is released, send
{"type": "flush"}(session.flush()in JavaScript,await session.flush()in Python).
Keep the finals and the partials apart, and draw both. The SDKs do the bookkeeping for you: session.text holds the final sentences, one per line, and session.partial the sentence being spoken, so you only redraw after each transcript message:
import asyncio
from voice213 import AsyncVoice213
async def main():
client = AsyncVoice213() # reads VOICE213_API_KEY
async with client.speech_to_text.live.connect(language="ar", dialect="algerian") as session:
sender = asyncio.create_task(session.send_file("call.wav"))
async for event in session:
if event.type == "transcript":
# The final sentences so far, then the sentence being spoken ("" between sentences)
print(session.text, session.partial, sep="\n")
await sender
asyncio.run(main())import Voice213 from "@voice213/sdk";
const voice213 = new Voice213(); // reads VOICE213_API_KEY
const session = await voice213.speechToText.live.connect({ language: "ar", dialect: "algerian" });
session.on("transcript", () => {
// The final sentences so far, then the sentence being spoken ("" between sentences)
console.log(session.text, session.partial);
});
await session.sendFile("call.wav");Without an SDK, keep a list of the finals in order and the current partial of each segment, as described in Transcripts.
Custom vocabulary
Names are the hardest words to catch. When you create the token, list the ones your speakers will say in vocabulary: your brand, your products, people and places.
{
"language": "ar",
"dialect": "algerian",
"vocabulary": ["Voice213", "Yalidine", "Baridimob", "Ouled Fayet"]
}Up to 50 terms, each 1 to 40 characters long, and duplicates are dropped. Anything else gets 400 INVALID_VOCABULARY. language and dialect take the same values as for files: see Languages and dialects.
Ending and billing
Send {"type": "end"} when you're done (await session.end() with the SDKs, which returns the ended message). Sent before ready, it isn't lost: the session starts all the same, transcribes the audio it held, and ends right after ready, billed like any other session. A session can also end on its own, and the ended message says why, in reason:
reason | Why the session ended |
|---|---|
client_ended | You sent end. |
max_duration | It reached the maxSeconds set on its token, one hour at most. A warning with the code ENDING_SOON comes about 30 seconds before. |
credit_limit | Your API credit couldn't cover more audio. An ENDING_SOON warning usually comes first. |
idle | No audio arrived for 60 seconds. |
connection_lost | Your socket closed or dropped without end, or your client sent a message over 64 KB, which makes Voice213 drop the connection. |
engine_error | The transcription failed and couldn't recover. Start a new session. |
server_restart | Voice213 restarted. Start a new session. |
What you pay:
- The audio you send, per second, rounded up to the whole second, from the first frame to the last, silences included.
- At least 15 seconds per session that received any audio. A session without audio costs nothing, and so does one that couldn't start.
- Once, at the end, whatever the reason,
connection_lost,engine_errorandserver_restartincluded. Theendedmessage has the amounts:audioSeconds,billableSeconds,costandremainingCredit. Afterconnection_lostyour client can't receive it, and a session stopped for breaking a rule, such asTOO_FAST, gets anerrormessage instead, but both are billed all the same.
While a session runs, Voice213 sets aside from your API credit the price of the audio received so far plus the next two minutes (never more than the session's limit), and keeps that amount up to date as the audio arrives. Your other requests can't spend it, and a session never ties up the rest of your balance. When your credit can't cover what comes next, the session's limit shrinks to what it covers, and the session ends there with credit_limit. To start, a session needs 15 seconds' worth of available credit: 1.25 DA.
Limits
| Limit | KhasbhaSTT | KhasbhaSTT LIVE |
|---|---|---|
| Longest audio | 30 minutes per file | 1 hour per session |
| Largest file | 100 MB, uploaded or at a URL | — |
| Audio | Audio and video files | 16-bit PCM, mono, 16 kHz, streamed |
| At once | 20 per key, shared with voice-overs | 5 sessions per account |
| Requests per minute and per day | Each transcription counts once Voice213 starts reading its audio, even if it's then refused | Each token counts once |
| Downloading a URL | Within 60 seconds | — |
| Session token | — | Single use, valid 2 minutes |
| Custom vocabulary | — | Up to 50 terms of up to 40 characters |
| Without audio | — | A session ends after 60 seconds |
| Socket messages | — | Up to 64 KB each |
- 5 sessions at once per account. Another token gets
429 SESSION_LIMITuntil one of them ends. Sessions don't take your account's 20 places for requests running at once. - Each token counts as one request toward your account's requests per minute and per day. Asking for one isn't billed, and the session itself doesn't count as a request.
- Real-time pace. Stream audio as it's recorded. More than 10 seconds ahead of real time, a session ends with
TOO_FAST. To transcribe a recording you already have, send it to KhasbhaSTT. - Pauses. While speech to text is paused for the API, new tokens and sessions are refused with
TOOL_DISABLED. Sessions already running carry on to their end.
Next steps
Was this page helpful?