JavaScript & TypeScript
@voice213/sdk: voice-overs, transcription and live sessions from Node.js, Bun, Deno, edge runtimes and the browser
@voice213/sdk is the official Voice213 SDK for JavaScript and TypeScript. It covers the whole developer API: voice-overs, KhasbhaSTT transcription, KhasbhaSTT LIVE sessions, the catalogue and your account. It runs on Node.js 18 and later, Bun, Deno and edge runtimes, with ES modules or CommonJS, and has no dependencies. Its types are included.
npm install @voice213/sdkimport Voice213 from "@voice213/sdk";
const voice213 = new Voice213(); // reads VOICE213_API_KEY
const speech = await voice213.textToSpeech.create({ text: "مرحبا بيكم في Voice213", voice: "kenza", model: "voice213-pro-2" });
await speech.save("welcome.mp3");
const transcript = await voice213.speechToText.transcribe({ file: "call.mp3", language: "ar", dialect: "algerian" });
console.log(transcript.text);With CommonJS, const { Voice213 } = require("@voice213/sdk"); gives you the same client.
Your API key
new Voice213() reads your key from the VOICE213_API_KEY environment variable: see Get Your API Key to create one and set it. To take it from somewhere else, such as a secret manager, pass it: new Voice213({ apiKey }). The key is checked when a request needs it: without one, the request fails before it's sent, with the code MISSING_API_KEY. Health needs no key.
The key pays for every request from your API credit. Keep it on your server: the client refuses to run in a web page, with the code BROWSER_NOT_ALLOWED. To transcribe live in a browser, your server creates a single-use token and the page uses LiveSession: see Live transcription in a browser.
Voice-overs
textToSpeech.create() turns a script into a voice-over, with any of the five models and the 30 voices:
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const speech = await voice213.textToSpeech.create({
text: "(نبرة حماسية) العرض راهو متوفر غير هاد السيمانة!",
voice: "ryad", // one of the 30 voices: voice213.voices.list()
model: "voice213-pro-2", // voice213-lite (the default), -lite-2, -pro, -pro-1.5 or -pro-2
dialect: "algerian", // algerian (the default), tunisian or libyan
targetDurationSeconds: 15, // optional: about 15 seconds, to fit a video
});
await speech.save("ad.mp3"); // Node.js, Bun and Deno
console.log(speech.audioUrl, `${speech.cost} DA`, `${speech.remainingCredit} DA left`);Tone directions in parentheses, such as (نبرة حماسية), are performed, not read, and aren't billed: see Tone Directions. Text to Speech describes every parameter, and what each one costs.
The speech
create() returns a Speech, with the same properties whichever format the API answered in:
| Property | Value |
|---|---|
audioUrl | A link to the MP3, also saved to your History in the web app. With inline, a data: URL carrying the WAV |
format, contentType | mp3 and audio/mpeg, or wav and audio/wav with inline |
stored | Whether the voice-over was saved to your History |
model, voice | The model and the voice that spoke |
cost, currency | What it cost, in dinars (DZD) |
chars, billableChars | The characters counted, and the characters billed: 100 at least |
words | The words spoken |
remainingCredit | Your API credit after the request |
raw | The answer, as the API sent it |
| Method | What it does |
|---|---|
save(path) | Writes the audio to path, creating its folder if needed, and returns the path. Node.js, Bun and Deno |
bytes() | The audio as a Uint8Array, in any runtime. It's downloaded once, then kept |
arrayBuffer(), blob() | The audio as an ArrayBuffer, or as a Blob typed audio/mpeg or audio/wav |
Inline audio
Pass inline: true to get the audio inside the answer, as a WAV file. Nothing is stored, and targetDurationSeconds doesn't apply:
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const speech = await voice213.textToSpeech.create({ text: "مرحبا بيكم في Voice213", voice: "nariman", inline: true });
await speech.save("speech.wav"); // speech.format is "wav"Price a script first
textToSpeech.estimate() tells you what a voice-over would cost on a model, without generating it, and whether your API credit covers it. It's free:
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const quote = await voice213.textToSpeech.estimate({ text: "مرحبا بيكم في Voice213", model: "voice213-pro-2" });
console.log(`${quote.billableChars} characters, ${quote.cost} DA`, quote.enough ? "" : "(top up first)");The quote has model, chars, billableChars, pricePer1MChars, cost, currency, balance and enough. See Estimate Cost.
Speech to text
speechToText.transcribe() sends a recording to KhasbhaSTT and returns its transcript. Pass the file as file, or the link to a recording that's already online as url:
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const transcript = await voice213.speechToText.transcribe({
file: "interview.mp4", // a path, bytes, a Blob or File, or a stream
language: "ar", // ar (the default), fr or en
dialect: "algerian", // for Arabic: algerian (the default), tunisian or libyan
speakers: true, // "المتحدث 1:" before each speaker's lines
onUploadProgress: ({ loaded, total }) => total && console.log(`${Math.round((100 * loaded) / total)} %`),
});
console.log(transcript.text);
console.log(`${transcript.billableSeconds} s billed, ${transcript.cost} DA`);
// A recording that's already online: Voice213 downloads it
const fromLink = await voice213.speechToText.transcribe({ url: "https://cdn.example.com/calls/2026-11-20-1432.mp3" });
console.log(fromLink.text);filetakes a path (in Node.js, Bun and Deno, streamed from disk), aUint8ArrayorBuffer, anArrayBuffer, aBloborFile, a webReadableStream, or a Node.js stream. The file's name and type come from the path or theFile; for bytes and streams, set them withfilenameandcontentType.- The other fields of
POST /sttare parameters too:model,language,dialect,speakers,punctuationandprofanity, with booleans as booleans. onUploadProgressis called as the file goes out: for every chunk in Node.js, and once it's sent elsewhere.totalis missing for a stream.- The transcript has
text,model,language,dialect,durationSeconds,billableSeconds,cost,currencyandremainingCredit.
A long recording can take a few minutes to upload and transcribe. The SDK waits up to 10 minutes for the answer, and in Node.js it isn't cut off after 5 minutes, as the built-in fetch is. A file sent as a stream can't be read twice, so it's never retried: pass a path or bytes when you can.
Price a recording
speechToText.estimate() prices audio from its length, free, as a file or as a live session:
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
// Ten minutes of audio, as a recording and as a live session
for (const model of ["khasbha-stt", "khasbha-stt-live"]) {
const quote = await voice213.speechToText.estimate({ durationSeconds: 600, model });
console.log(model, `${quote.billableSeconds} s, ${quote.cost} DA`, quote.enough);
}Live transcription
KhasbhaSTT LIVE writes speech down while it's spoken. A session is a single-use token and one socket. speechToText.live.connect() creates both, and returns a LiveSession that streams your audio and gives you the transcript. See KhasbhaSTT LIVE for how sessions work and what they cost.
From a server, a script or a phone bridge
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const session = await voice213.speechToText.live.connect({
language: "ar",
dialect: "algerian",
vocabulary: ["Yalidine", "Baridimob"], // names to recognize
maxSeconds: 900, // your own cap on the session
});
session.on("transcript", ({ text, final }) => final && console.log(text));
session.on("warning", ({ secondsLeft }) => console.log(`${secondsLeft} s left`));
// A WAV file at real-time pace, then the summary
const summary = await session.sendFile("call.wav");
console.log(`${summary.billableSeconds} s billed, ${summary.cost} DA`);
console.log(session.text); // every final sentence, one per lineconnect()takes the token's fields, all optional:language,dialect,vocabulary,maxSeconds, andoriginfor a browser. See Create a Live Token. It returns as soon as the socket is on its way: audio you send meanwhile waits, up to its last 5 seconds.sendFile()reads a WAV file of any common encoding, sample rate and channel count, sends it as 16 kHz mono at real-time pace, then ends the session and returns theendedsummary. With{ end: false }, it leaves the session open. It takes a path, bytes or aBlob. Convert other formats to WAV first, for example withffmpeg -i call.mp3 -ar 16000 -ac 1 -c:a pcm_s16le call.wav.- To stream audio yourself, call
send(pcm)with 16 kHz, 16-bit mono PCM, anInt16Arrayor its bytes, at the pace it's recorded.flush()finalizes the sentence being spoken, andawait session.end()finishes and returns the summary. for await (const message of session)reads every message from the server, if you prefer it to events.- Node.js 21 and older have no built-in WebSocket:
npm install ws, then pass it withnew Voice213({ WebSocket }), afterimport WebSocket from "ws".
A phone line
A phone call arrives as 8 kHz μ-law. decodeMulaw() and a resampler turn it into the 16 kHz PCM a session takes. Here with Twilio Media Streams, whose <Stream> sends the call to your server over a WebSocket:
// npm install @voice213/sdk ws
import Voice213, { LiveSession, createResampler, decodeMulaw } from "@voice213/sdk";
import WebSocket, { WebSocketServer } from "ws";
const voice213 = new Voice213();
// Twilio connects here: <Stream url="wss://your-server.example/media" />
const server = new WebSocketServer({ port: 8080, path: "/media" });
server.on("connection", (twilio) => {
// The session opens as soon as its token arrives: the call's first words wait for it
const token = voice213.speechToText.live.createToken({ language: "ar", dialect: "algerian" });
const session = new LiveSession(token, { WebSocket });
const to16k = createResampler(8000, 16000);
session.on("transcript", ({ text, final }) => final && console.log(text));
twilio.on("message", (raw) => {
const event = JSON.parse(raw);
if (event.event === "media") session.send(to16k.process(decodeMulaw(Buffer.from(event.media.payload, "base64"))));
if (event.event === "stop") session.end();
});
});new LiveSession() takes the token, its url, or a promise of either, so the audio can start before the token is ready.
Live transcription in a browser
Your server creates a single-use token with your key, for your page's origin, and hands the page only the token's url:
import express from "express";
import Voice213, { APIError } from "@voice213/sdk";
const app = express();
const voice213 = new Voice213();
app.post("/api/live-token", async (req, res) => {
// Check here that the visitor is one of your signed-in users
try {
const token = await voice213.speechToText.live.createToken({ language: "ar", maxSeconds: 600, origin: "https://shop.example" });
res.json({ url: token.url });
} catch (error) {
res.status(error instanceof APIError ? error.status : 502).json({ error: error.message });
}
});
app.listen(8080);In the page, LiveSession opens the session with that url, and startMicrophone() streams the microphone:
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 url from your server: the session opens as soon as it arrives
const url = fetch("/api/live-token", { method: "POST" }).then((response) => response.json()).then((token) => token.url);
const session = new LiveSession(url);
session.on("transcript", () => {
transcript.textContent = session.text; // the final sentences
draft.textContent = session.partial; // the sentence being spoken
});
session.on("error", (error) => (draft.textContent = error.message));
try {
await session.startMicrophone(); // in the click: browsers start audio only from a gesture
} catch (error) {
session.close();
draft.textContent = error.message; // MIC_DENIED: the visitor refused the microphone
return;
}
stopButton.onclick = () => session.end();
};- Call
startMicrophone()from a user gesture, such as a click: browsers only start audio from one, and only on secure pages (HTTPS, orlocalhost). - It captures the microphone at 16 kHz in an AudioWorklet, with an anti-aliasing filter, and streams it in frames of 40 ms. Its options are
deviceId, andechoCancellation,noiseSuppressionandautoGainControl, all on by default. - It returns a
Microphone, withlevel(0 to 1, for a meter),muted(set it to send silence),streamandstop().end(),close()and the end of the session stop it too. - Its errors have the codes
MIC_DENIED(the visitor refused),MIC_UNAVAILABLE(no microphone could be opened) andUNSUPPORTED(no HTTPS, or no AudioWorklet). - The worklet loads from a
blob:URL. If your Content-Security-Policy blocksblob:scripts, serve@voice213/sdk/microphone-worklet.jsfrom your site, and pass its address:session.startMicrophone({ workletUrl: "/microphone-worklet.js" }). - Without a bundler, import the SDK from a CDN, pinned to a version:
https://cdn.jsdelivr.net/npm/@voice213/sdk@0.1.0/+esm. See the complete page.
The session
| Property | Value |
|---|---|
status | connecting, starting (the socket is open, the session is starting), live, ending (after end()), then ended. Or failed, or closed after close() |
text | Every final sentence so far, one per line |
partial | The sentence being spoken, as heard so far: "" between sentences |
sessionId, maxSeconds | From ready: the session's id, and how long it can last |
ready | A promise of the ready message |
finished | A promise of the ended summary. It rejects with a LiveSessionError when the session fails |
| Method | What it does |
|---|---|
send(pcm) | Sends 16 kHz, 16-bit mono PCM: an Int16Array, or its bytes. Sent before the socket opens, the last 5 seconds wait and go first |
sendFile(source, options) | Streams a WAV file, or raw 16 kHz PCM, at real-time pace, then ends the session and returns the summary |
flush() | Finalizes the sentence being spoken, without waiting for the silence after it |
end() | Finishes: the microphone stops, the last final sentences arrive, then the summary, which it returns |
close() | Closes the socket without end. The audio received is billed, and no summary comes |
ping() | Asks the server for a pong message |
startMicrophone(options) | In a browser, streams the microphone (above) |
on(event, listener), once(event, listener), off(event, listener) | Listen to an event. on and once return a function that stops listening |
| Event | Payload |
|---|---|
ready | sessionId, model, language, dialect, maxSeconds, sampleRate |
transcript | segment, text and final: a partial, or a sentence's final text |
warning | code (ENDING_SOON) and secondsLeft, 30 seconds or less before the session ends |
ended | The summary: sessionId, reason, audioSeconds, billableSeconds, cost, currency, remainingCredit |
error | A LiveSessionError |
close | code and reason: the socket closed |
message | Every message from the server |
See Live Transcription Socket for what each message, end reason and error code means.
The catalogue and your account
import Voice213 from "@voice213/sdk";
const voice213 = new Voice213();
const { voices, defaultVoice } = await voice213.voices.list(); // the 30 voices
const { categories, tones } = await voice213.tones.list(); // tone directions, by ad stage
const { models, defaultModel } = await voice213.models.list(); // voice models and their prices
const sttModels = await voice213.speechToText.models.list(); // KhasbhaSTT and KhasbhaSTT LIVE
const { credit, key } = await voice213.account.get(); // your API credit, and your account's limits
const { ok } = await voice213.health(); // needs no key
console.log(voices.length, defaultVoice, categories.length, Object.keys(tones), models.length, defaultModel);
console.log(sttModels.models.length, credit, key.rateLimit.rpd, ok);They're free, and rarely change: read them once and keep the answer. The answers are the API's, without success, with the voices and the tones taken out of the data the API wraps them in, and account.get() flattens GET /me to credit, currency and key.
Errors
Every error the SDK throws is a Voice213Error, with a code to branch on and a message in English, even when the API's own is in Arabic. Answers from the API are APIErrors, one class per status:
import Voice213, { InsufficientCreditError, RateLimitError, Voice213Error } from "@voice213/sdk";
const voice213 = new Voice213();
try {
await voice213.textToSpeech.create({ text: "مرحبا بيكم في Voice213" });
} catch (error) {
if (error instanceof InsufficientCreditError) {
console.log(`Top up: ${error.required} DA needed, ${error.balance} DA available`);
} else if (error instanceof RateLimitError && error.code === "RATE_LIMIT_DAY") {
console.log("Daily limit reached: try again tomorrow");
} else if (error instanceof Voice213Error) {
console.log(error.code, error.message);
} else {
throw error;
}
}| Class | Status | Codes include |
|---|---|---|
BadRequestError | 400 | UNKNOWN_VOICE, UNKNOWN_MODEL, EMPTY_TEXT, TEXT_TOO_LONG, TOO_MANY_WORDS, INVALID_MEDIA, AUDIO_TOO_LONG… |
AuthenticationError | 401 | INVALID_API_KEY, MISSING_API_KEY |
InsufficientCreditError | 402 | INSUFFICIENT_CREDIT |
PermissionDeniedError | 403 | API_ACCESS_BLOCKED, ACCOUNT_DEACTIVATED |
NotFoundError, EndpointRemovedError, PayloadTooLargeError | 404, 410, 413 | NOT_FOUND, ENDPOINT_REMOVED, FILE_TOO_LARGE |
RateLimitError | 429 | RATE_LIMIT_MINUTE, RATE_LIMIT_DAY, RATE_LIMIT_CONCURRENT, SESSION_LIMIT, RATE_LIMITED |
InternalServerError | 500, 502, 504 | TRANSCRIPTION_FAILED, GENERATION_FAILED, INTERNAL_ERROR |
ServiceUnavailableError | 503 | MODEL_DISABLED, TOOL_DISABLED, MAINTENANCE |
APIConnectionError, APITimeoutError | — | CONNECTION_ERROR, TIMEOUT |
LiveSessionError | — | The socket's codes (TOO_FAST, SESSION_LIMIT…), CONNECTION_FAILED, CONNECTION_LOST, CLOSED |
- Every
APIErrorhas thestatus, the answer'sbodyandheaders, andretryAfter: the seconds of theRetry-Afterheader, ornull. InsufficientCreditErroraddsrequiredandbalance, in dinars, andcurrency.RateLimitErroraddslimit.ServiceUnavailableErroraddsendsAtfor maintenance,toolforTOOL_DISABLEDandmodelforMODEL_DISABLED.LiveSessionErroraddscloseCode, the socket's close code.APITimeoutErrormeans no answer came in time. A voice-over or a transcription may still finish and be charged: raisetimeoutrather than sending it again.- Problems caught before any request is sent are plain
Voice213Errors, such asMISSING_API_KEY,INVALID_FILE(nofileorurl, or both),FILE_NOT_FOUNDandUNSUPPORTED_AUDIO.
See Errors for what each code means and what to do about it.
Retries and timeouts
The SDK retries what can succeed on a second attempt, twice by default, after the API's Retry-After when it sends one (a minute at most), and with exponential backoff otherwise:
429, except your account's daily limit (RATE_LIMIT_DAY), which won't clear today;500,502,503and504, except a paused model (MODEL_DISABLED): use another model;- a connection that failed before the request reached Voice213, and, for the free requests, any connection error or timeout.
A voice-over or a transcription that may have reached Voice213, but whose answer never came, is never sent again: Voice213 finishes it and charges it even when your client stops waiting, so a second attempt could pay twice. Give long requests time instead:
import Voice213 from "@voice213/sdk";
// Every request: up to 4 retries, and 15 minutes for an answer
const voice213 = new Voice213({ maxRetries: 4, timeout: 15 * 60 * 1000 });
// One request: 20 minutes for an answer, and cancelled after 30 whatever happens
const transcript = await voice213.speechToText.transcribe(
{ file: "meeting.mp3" },
{ timeout: 20 * 60 * 1000, signal: AbortSignal.timeout(30 * 60 * 1000) }
);
console.log(transcript.text);Every method takes { timeout, maxRetries, signal, headers } as its last argument, for that request only. See Handle errors and retry safely.
Configuration
| Option | Default | What it sets |
|---|---|---|
apiKey | VOICE213_API_KEY | Your API key |
baseURL | VOICE213_BASE_URL, else https://api.voice213.com | The API's address |
timeout | 10 minutes | How long to wait for an answer, in milliseconds |
maxRetries | 2 | How many times to retry a failure that can succeed on a later attempt |
defaultHeaders | None | Headers sent with every request |
fetch | node:https in Node.js, Bun and Deno, fetch elsewhere | The function that sends requests. Node's built-in fetch would bring back its 5-minute limit |
WebSocket | The runtime's | A WebSocket class for live sessions, such as the ws package's in Node.js 21 and older |
Audio helpers
The functions the SDK uses for live audio are exported, for your own pipelines:
| Export | What it does |
|---|---|
LIVE_SAMPLE_RATE | 16000, the sample rate a live session takes |
toLivePcm(bytes) | A WAV file (any common encoding, rate and channel count) or raw PCM, as 16 kHz 16-bit mono PCM: an Int16Array ready for send() |
readWav(bytes) | A WAV file's sampleRate, channels and pcm, mixed down to mono |
decodeMulaw(bytes), encodeMulaw(pcm) | G.711 μ-law, the codec of phone lines, to 16-bit PCM, and back |
createResampler(fromRate, toRate) | A resampler for a stream: call its process(pcm) with each chunk in turn |
resamplePcm16(pcm, fromRate, toRate) | Resamples a whole recording at once |
floatToPcm16(samples), pcm16ToFloat(pcm) | Web Audio's Float32Array samples to 16-bit PCM, and back |
TypeScript
Every parameter and answer is typed, with its documentation in your editor. The types are exported by name, such as TextToSpeechParams, Transcription, LiveToken and LiveServerMessage:
import Voice213, { type TextToSpeechParams, type Transcription } from "@voice213/sdk";
const voice213 = new Voice213();
const params: TextToSpeechParams = { text: "مرحبا بيكم في Voice213", voice: "kenza", model: "voice213-pro-2" };
const speech = await voice213.textToSpeech.create(params);
const transcript: Transcription = await voice213.speechToText.transcribe({ file: "call.mp3" });
console.log(speech.cost, transcript.text);Next steps
Was this page helpful?