Skip to content
WSS
wss://api.voice213.com/ws/stt

The protocol behind KhasbhaSTT LIVE, for clients in any language: a server, a mobile app, a phone system, a device. A session is a single-use token from your server, then one WebSocket that takes audio as binary frames and sends the transcript back as small JSON messages.

The JavaScript and Python SDKs implement this protocol for you, as the examples below show; this page remains the reference for clients in other languages, and for what each message means.

​1. Get a token

POST https://api.voice213.com/api/v1/stt/live/token
Authorization: Bearer sk_live_...
Content-Type: application/json

{ "language": "ar", "dialect": "algerian", "vocabulary": ["Yalidine"], "maxSeconds": 600 }
{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
  "url": "wss://api.voice213.com/ws/stt?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
  "wsUrl": "wss://api.voice213.com/ws/stt",
  "expiresIn": 120,
  "model": "khasbha-stt-live",
  "language": "ar",
  "dialect": "algerian",
  "maxSeconds": 600,
  "sampleRate": 16000,
  "encoding": "pcm_s16le",
  "channels": 1,
  "pricePerMinute": 5,
  "minBillableSeconds": 15,
  "currency": "DZD"
}

The token opens one session, within two minutes. The session's settings travel inside it, so they're fixed once the socket is open: to change the language or the vocabulary, end the session and create a new token. A token created with an origin only opens a socket from that origin. See Create a Live Token.

​2. Connect

wss://api.voice213.com/ws/stt?token=<token>

Open url, which already carries the token, or wsUrl with the token as the token query parameter. A handshake that can't go ahead is refused with an HTTP status, before any socket opens:

StatusWhen
401The token is missing, invalid, expired or already used, or the socket's Origin header isn't the token's origin. Create a new token.
503Voice213 is restarting. Retry in a few seconds, with a new token.

The server then starts the session. It checks that your account and your API key are active, that speech to text isn't paused, that you have a session free, and that your API credit covers at least 15 seconds of audio, then connects the transcription. This takes a moment. When the session is live, the server sends ready:

{
  "type": "ready",
  "sessionId": "stt_5f0c2a9e7b13d8466a1c04fe",
  "model": "khasbha-stt-live",
  "language": "ar",
  "dialect": "algerian",
  "maxSeconds": 600,
  "sampleRate": 16000
}

maxSeconds is how long this session can last: the maxSeconds set on the token (3,600 when you set none), or less when your available API credit covers less as the session starts. If the session can't start, the server sends an error message instead and closes the socket with code 4000. Nothing is billed.

​3. Stream audio

​Audio

WhatRule
Format16-bit signed little-endian PCM (pcm_s16le), mono, 16,000 Hz: 32,000 bytes a second
FramesBinary messages, best at 20 to 100 ms each (640 to 3,200 bytes). At most 64 KB, and always a whole number of samples: an even number of bytes
PaceReal time: send the audio as it's recorded
  • Start right away. Audio that arrives before ready is held, up to 5 seconds of it, and transcribed once the session is live, so the first words aren't lost. Anything beyond those 5 seconds sent before ready is dropped, and isn't billed.
  • Keep streaming during silence. A sentence is finalized when the silence after it is heard. If your audio stops, for example when a push-to-talk button is released, send flush to finalize what was said.
  • Stay at real-time pace. Real time counts from the moment the socket opened, and up to 10 seconds ahead of it is tolerated, to absorb network hiccups. Further ahead, the session ends with TOO_FAST.
  • Whole samples only. A frame with an odd number of bytes ends the session with INVALID_AUDIO. A message over 64 KB makes Voice213 drop the connection: your client sees the close code 1006, and the session ends as connection_lost.
  • Binary or base64. If your platform can't send binary frames, send { "type": "audio", "data": "<base64 PCM>" }, with the same rules for the audio inside. data that isn't valid base64 ends the session with INVALID_AUDIO. Base64 makes a message a third larger: frames of 20 to 100 ms stay far below the limit.
  • Every byte is billed, silence included: end the session when you no longer need it.

​Messages from you

MessageEffect
A binary frameAudio: 16-bit PCM, mono, 16 kHz
{ "type": "audio", "data": "<base64>" }The same audio, base64-encoded, for clients that can't send binary frames
{ "type": "flush" }Finalize the current sentence now, without waiting for the silence after it
{ "type": "end" }Finish. The last final transcripts arrive, then ended, then the server closes the socket with 1000. Sent before ready, it waits for the session to start: see End.
{ "type": "ping" }Answered with { "type": "pong" }, if you want an application-level heartbeat

Messages of any other type are ignored.

​Messages from the server

MessageMeaning
{ "type": "ready", "sessionId", "model", "language", "dialect", "maxSeconds", "sampleRate" }The session is live
{ "type": "transcript", "segment", "text", "final": false }A partial transcript. It replaces the previous partial of the same segment.
{ "type": "transcript", "segment", "text", "final": true }The segment's final text. Append it. The next sentence has segment + 1.
{ "type": "warning", "code": "ENDING_SOON", "secondsLeft" }Sent once, when the session has 30 seconds or less left: its time limit is near, or your API credit is running out. secondsLeft is usually 30.
{ "type": "ended", "sessionId", "reason", "audioSeconds", "billableSeconds", "cost", "currency", "remainingCredit" }The session is over, and billed. See End. It isn't sent after an error.
{ "type": "error", "code", "message" }The session couldn't start, broke a rule, or failed on our side. A close follows. Branch on code: message is a readable English sentence.
{ "type": "pong" }The answer to your ping

Every message from the server is JSON, in a text frame.

​Transcripts

Each sentence is a segment, numbered from 0. Its partial transcripts replace one another while it's spoken; its final transcript comes when the speaker pauses, or when you send flush or end, and is never revised. Build the transcript from the finals, in order, and show the current partial after them. A short sentence can come as a final without partials. The SDKs keep both for you, as text and partial: see Partial and final transcripts.

{ "type": "transcript", "segment": 3, "text": "واش نقدر", "final": false }
{ "type": "transcript", "segment": 3, "text": "واش نقدر نبدلها", "final": false }
{ "type": "transcript", "segment": 3, "text": "واش نقدر نبدلها بنمرة أكبر؟", "final": true }

​4. End

Send { "type": "end" } and wait for ended: the server sends the last final transcripts first, then ended, then closes the socket with code 1000.

{
  "type": "ended",
  "sessionId": "stt_5f0c2a9e7b13d8466a1c04fe",
  "reason": "client_ended",
  "audioSeconds": 123.45,
  "billableSeconds": 124,
  "cost": 10.3333,
  "currency": "DZD",
  "remainingCredit": 989.67
}

An end sent before ready isn't lost. The session starts all the same, and right after ready the server transcribes the audio it held, then ends the session the same way, with the reason client_ended. It's billed like any other session. If the session can't start, you get an error and the close code 4000 instead, and nothing is billed.

Closing the socket without end also ends the session, with the reason connection_lost. The audio received is billed all the same, but you don't get ended.

The server pings every connection every 15 seconds at the WebSocket level, and drops connections that stop answering. WebSocket libraries answer these pings for you.

​End reasons

reasonWhy the session ended
client_endedYou sent end.
max_durationIt reached the maxSeconds set on the token, one hour at most: that much audio, or that much time since ready plus 10 seconds.
credit_limitYour API credit couldn't cover more audio.
idleNo audio arrived for 60 seconds.
connection_lostYour socket closed or dropped without end or stopped answering pings, or your client sent a message over 64 KB. You don't receive ended.
engine_errorThe transcription failed and couldn't recover. Start a new session.
server_restartVoice213 restarted, for an update for example. Start a new session.

Before max_duration and credit_limit, the ENDING_SOON warning usually comes first. A session ended for breaking a rule (INVALID_AUDIO, TOO_FAST) or by an error on our side (INTERNAL) gets an error message instead of ended, and is billed all the same for the audio received.

​Billing

A session is billed once, when it ends, whatever the reason:

  • audioSeconds is the audio received: its bytes ÷ 32,000, up to the session's limit.
  • billableSeconds is audioSeconds rounded up to the whole second (a remainder of 0.05 s or less isn't counted), and at least 15. It's 0 when no audio arrived.
  • cost is billableSeconds × pricePerMinute ÷ 60, rounded to four decimals, in dinars, at the price in force when the socket opened. At 5 DA a minute, 124 seconds cost 10.3333 DA.
  • A session that couldn't start (close code 4000) costs nothing.

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, so your other requests can't spend it. A session never ties up the rest of your balance, and never runs past what your credit covers: when your credit can't cover what comes next, the session's limit shrinks to what it covers, and it ends there with credit_limit. See API Pricing & Limits for the prices.

​Close codes and errors

Close codeMeaning
1000The session ended (client_ended, max_duration, credit_limit or idle). ended came just before.
1008The client broke a rule: INVALID_AUDIO or TOO_FAST. The error message before it says which, and no ended comes.
1011The session failed on our side: ended came first with the reason engine_error, or an error with the code INTERNAL. Start a new session.
1012Voice213 is restarting: ended came first, with the reason server_restart. Start a new session.
4000The session couldn't start. The error message before it says why. Nothing is billed.
1006The connection dropped without a close: a network failure, or a message over 64 KB. The session ends with connection_lost.

Whatever the close code, a session that received audio is billed once for it, except one that never started (4000).

error codeWhat happenedWhat to do
INSUFFICIENT_CREDITYour available API credit can't cover 15 seconds of audio, 1.25 DATop up
SESSION_LIMITYour account already has 5 sessions runningEnd one, or retry when one has ended
BUSYVoice213 can't take more live sessions right nowRetry in a moment
TOOL_DISABLEDSpeech to text through the API is pausedRetry later
MAINTENANCEVoice213 is down for maintenanceRetry later
ACCOUNT_BLOCKEDThe account that owns the key is deactivated or suspended, or its API access is switched offContact support
KEY_REVOKEDThe API key that created the token has been switched off or deletedCreate a token with an active key
ENGINE_UNAVAILABLEThe live transcription service is unavailableRetry in a moment
INVALID_AUDIOA frame had an odd number of bytes, or an audio message's data wasn't base64Send whole 16-bit samples
TOO_FASTThe audio got more than 10 seconds ahead of real time, counted from when the socket openedSend audio at the pace it's recorded
INTERNALSomething went wrong on our sideRetry with a new session

​Example: Python

A complete client with the Python SDK: it streams call.wav at real-time pace, prints each sentence as it's finalized, and saves the transcript to call.txt. send_file() reads a WAV file at any sample rate and sends it as 16 kHz, 16-bit mono frames of 100 ms; convert other formats first, for example with ffmpeg -i call.mp3 -ar 16000 -ac 1 -c:a pcm_s16le call.wav.

# pip install voice213
import asyncio

from voice213 import AsyncVoice213, Voice213Error


async def main():
    client = AsyncVoice213()  # reads VOICE213_API_KEY
    session = None
    try:
        # Creates the token, then opens the socket with it
        async with client.speech_to_text.live.connect(
            language="ar", dialect="algerian", vocabulary=["Yalidine", "Baridimob"], max_seconds=900
        ) as session:
            # Streams the file at real-time pace, sends `end`, and returns the `ended` message
            sender = asyncio.create_task(session.send_file("call.wav"))
            async for event in session:  # every message from the server, until the socket closes
                if event.type == "ready":
                    print(f"session {event.session_id}, up to {event.max_seconds} s")
                elif event.type == "transcript" and event.final:
                    # partials (final is False) replace each other: this script prints finals only
                    print(event.text)
                elif event.type == "warning":
                    print(f"{event.seconds_left} s left")
            summary = await sender
            print(f"{summary.reason}: {summary.billable_seconds} s billed, {summary.cost} DA, {summary.remaining_credit} DA left")
    except Voice213Error as error:
        # A refused token request, a refused handshake (the token was used, expired or wrong),
        # or an `error` message, such as SESSION_LIMIT or TOO_FAST
        print(f"{error.code}: {error.message}")

    if session:
        with open("call.txt", "w", encoding="utf-8") as out:
            out.write(session.text)  # the final sentences, one per line


asyncio.run(main())

​Example: browser

In a web app, LiveSession from the JavaScript SDK speaks this protocol: it opens the socket with the token's url, captures the microphone at 16 kHz in an audio worklet, streams the frames, and keeps the transcript. Your server creates the token, with a route like the one in From a browser, so the page never sees your API key. Start the session from a click.

import { LiveSession } from "@voice213/sdk";

const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const transcript = document.getElementById("transcript");
const draft = document.getElementById("draft");

startButton.onclick = async () => {
  // The socket's url from your token route: the session opens as soon as it arrives
  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("ready", ({ sessionId, maxSeconds }) => console.info(`session ${sessionId}, up to ${maxSeconds} s`));
  session.on("transcript", () => {
    transcript.textContent = session.text; // the final sentences, one per line
    draft.textContent = session.partial; // the sentence being spoken
  });
  session.on("warning", ({ secondsLeft }) => console.info(`${secondsLeft} seconds left in this session`));
  session.on("ended", ({ reason, billableSeconds, cost }) => console.log(reason, `${billableSeconds} s`, `${cost} DA`));
  session.on("error", ({ code, message }) => console.warn(code, message)); // the socket closes next

  try {
    // In the click: browsers start audio only from a user gesture
    await session.startMicrophone();
  } catch (error) {
    session.close();
    console.warn("Couldn't start:", error.message); // MIC_DENIED when the visitor refuses the microphone
    return;
  }
  // The microphone goes off at once. The server transcribes the audio it has, sends the last words and `ended`,
  // then closes the socket
  stopButton.onclick = () => session.end();
};

Audio captured before the socket opens waits in the page, up to its last 5 seconds, and goes first. After that, the microphone streams in frames of 40 ms, at the pace it records.

Was this page helpful?