API reference

Audio streaming protocol

Stream raw audio to a conversation over a WebSocket, from a server, a phone bridge or a mobile app.

The browser SDK speaks this protocol for you. Use it directly when your audio isn't in a browser: a server processing a call, a phone bridge, or a mobile app.

Each audio source is one WebSocket. Sparkle transcribes what you send, stores the turns, and sends interim text and finished turns back on the same connection.

No audio is stored, on disk, in Redis or in logs; only the turns transcribed from it are kept.

1. Mint a session

POST /conversations/{id}/audio-sessions, with your API key:

FieldValue
sourcelocal for the person running the capture, remote for everyone else.
encodinglinear16: 16-bit signed PCM, little-endian, mono.
sample_rate16000, 24000, 44100 or 48000.
languageOptional, such as en.

It answers 201 with url, token and expires_at. The url is the WebSocket to open, with the token in its query. The token works once, within 60 seconds: mint a new session for every connection, reconnects included. A refusal is an error with one of the codes under Refusals.

2. Stream

Open the url and wait for {"type":"ready"} before sending audio. Sparkle connects to its transcriber first, so ready can take up to 10 seconds; don't give up sooner.

You send:

FrameContent
BinaryPCM at the declared rate, up to 64 KB per frame. Send about 100 ms per frame, as it is captured.
Text{"type":"keepalive"} every 5 seconds while no audio flows, such as while muted.
Text{"type":"stop"} when you're done: Sparkle transcribes what it has, sends the last turns, then closed.

Sparkle sends, as JSON text frames:

typeFieldsMeaning
readyStart sending audio.
interimsource, textWhat is being heard; the next interim replaces it.
turnturn: id, speaker (key, name), text, start_s, end_sA finished turn, already stored. Times are seconds on the conversation's clock.
errorcode, messageWhy the connection is ending. The close frame follows it; closed doesn't.
closedAfter your stop, or before the server shuts down. The close frame follows.

Ignore message types you don't know: new ones may be added. Sparkle may skip interim messages when your side reads slowly; the next one replaces them anyway. turn messages are never skipped.

Speaker keys are local for a local source. On a remote source, the first voice heard is remote and each new one after it remote_1, remote_2 and so on, counted per connection. speaker.name can be null.

How a connection ends

Sparkle closes the socket with one of these close codes. When it ends on an error, the error message comes first and the close frame's reason repeats its code, so a client that missed the message can still read it.

Close codecodeRetry?
1000None: closed came first, after your stop.No: you're done.
1001None: closed came first, and the server is shutting down. The turns already heard are stored.Yes, on a new session.
1003audio.invalid_message: a text frame wasn't keepalive or stop.No. Fix the client.
1008audio.idle_timeout: neither audio nor a keepalive arrived for 30 seconds.No.
1008audio.session_limit: the socket ran as long as your plan lets one run.Yes, on a new session.
1008conflict.audio_source_streaming: another socket took over this source.Yes, on a new session, with backoff (see below).
1008limit.transcription_minutes or limit.test_transcription_minutes: the month's transcription minutes ran out before this socket metered any audio.No.
1008A refusal, such as conflict.conversation_ended or a limit.* code: the turns heard could not be stored.No.
1009audio.frame_too_large: a binary frame was over 64 KB.No. Send smaller frames.
1011bad_gateway.transcription: the transcriber couldn't be reached.Yes, on a new session, with backoff.
1011internal.server_error: the turns heard could not be stored.No.
1013audio.backpressure: turns arrived faster than they could be stored.Yes, on a new session, with backoff.

A connection that drops without a close frame (1006 in a browser) is retryable too.

Refusals

Minting a session, and opening the socket, are refused with an HTTP status and an error body. A browser can't read why a socket's handshake failed, so minting checks everything opening does, except the token:

StatuscodeWhen
503audio.not_configuredThis deployment transcribes no audio. Don't retry; send turns.
401unauthorized.audio_tokenOpening only: the token is unknown, already used, or past expires_at. Mint a new one.
409conflict.audio_source_streamingA socket is already streaming this source of the conversation.
409conflict.conversation_endedThe conversation has ended, or is an import still being processed.
400validation.audio.*source, encoding, sample_rate or language isn't one Sparkle takes.
403limit.transcription_minutesA live key on Free, after the month's 60 transcription minutes.
403limit.test_transcription_minutesA test key or the dashboard, after the month's test transcription minutes.
403, 429limit.*A plan limit, such as the month's minutes.
404not_found.conversationThe conversation doesn't exist, or belongs to another organization.

A socket holds its source while it streams, and a socket that drops without closing keeps holding it for up to 30 seconds. So a reconnect right after a drop can be refused with conflict.audio_source_streaming until then: retry it with backoff for about 35 seconds before giving up.

Transcription minutes

Every second of audio Sparkle's transcriber accepts counts toward the company's transcription minutes, per socket: streaming a call's local and remote sources meters its length twice. Pro and Scale pay $0.012 per stream-minute on live keys, billed per second. Free includes 60 a month on live keys, and test keys have their own monthly allowance; past either, new sessions are refused with limit.transcription_minutes or limit.test_transcription_minutes.

A socket that is already streaming is never cut off for transcription minutes. One that has not yet metered any audio when they run out closes with the code instead, as a new session would be refused.

Limits

  • One connection per source per conversation.
  • A connection with neither audio nor keepalives for 30 seconds is closed.
  • A binary frame holds at most 64 KB.
  • One connection runs at most as long as your plan allows; continue on a new session after it.

Example: stream a WAV file

A Node 22 script, with no dependencies, that streams a 16-bit mono WAV file in real time and prints the turns. Convert other audio first, for example with ffmpeg -i call.mp3 -ac 1 -ar 16000 -sample_fmt s16 call.wav.

stream-wav.mjs
import { readFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

const [conversationId, path] = process.argv.slice(2);
const wav = await readFile(path);

// A WAV file is a list of chunks: "fmt " describes the audio, "data" holds it.
let format;
let pcm;
for (let at = 12; at + 8 <= wav.length;) {
  const id = wav.toString("ascii", at, at + 4);
  const size = wav.readUInt32LE(at + 4);
  const body = wav.subarray(at + 8, at + 8 + size);
  if (id === "fmt ") {
    format = {
      pcm: body.readUInt16LE(0) === 1,
      channels: body.readUInt16LE(2),
      rate: body.readUInt32LE(4),
      bits: body.readUInt16LE(14),
    };
  }
  if (id === "data") pcm = body;
  at += 8 + size + (size % 2);
}
if (!format?.pcm || format.channels !== 1 || format.bits !== 16 || !pcm) {
  throw new Error("Expected 16-bit mono PCM: convert it with ffmpeg first.");
}

const minted = await fetch(
  `https://api.sparkle.ai/public/v1/conversations/${conversationId}/audio-sessions`,
  {
    method: "POST",
    headers: {
      "X-API-Key": process.env.SPARKLE_API_KEY,
      "Idempotency-Key": crypto.randomUUID(),
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ source: "remote", encoding: "linear16", sample_rate: format.rate }),
  }
);
if (!minted.ok) throw new Error(`audio session: ${minted.status} ${await minted.text()}`);
const { url } = await minted.json();

const socket = new WebSocket(url);
socket.addEventListener("message", async (event) => {
  const message = JSON.parse(event.data);
  switch (message.type) {
    case "ready": {
      const frame = (format.rate / 10) * 2; // 100 ms of 16-bit samples
      for (let at = 0; at < pcm.length; at += frame) {
        socket.send(pcm.subarray(at, at + frame));
        await sleep(100);
      }
      socket.send(JSON.stringify({ type: "stop" }));
      break;
    }
    case "turn": {
      const { start_s, speaker, text } = message.turn;
      console.log(`[${start_s.toFixed(1)}s] ${speaker.key}: ${text}`);
      break;
    }
    case "error":
      console.error(message.code, message.message);
      break;
    case "closed":
      socket.close();
      break;
  }
});
SPARKLE_API_KEY=spk_test_… node stream-wav.mjs cnv_2kd9c3f6j0m4q8u2y5bg call.wav

On this page