Guide · streaming

Listen

Follow a transcription as it happens, in any language: subscribe, catch up from a snapshot, then apply live frames in order.

Anyone allowed to read a transcription can follow it live over its subscribe socket: the owner with an API key, a reader with a share link's code, anyone at all on a public broadcast. The socket sends what changes from the moment it opens; what was said before is read once, from a snapshot. Getting the two to meet without a gap or a duplicate is the whole trick, and the cursor makes it exact.

  1. Find the transcription

    Subscribing takes a transcription id. The owner has it already: the transcription's id (the publish grant's transcription.id is the same), or a broadcast's currentTranscription.transcriptionId. Each press of Record on a broadcast makes a new transcription, so a screen waiting for a broadcast to go live opens its events socket (WS /v1/broadcasts/{id}/events, or /v1/transcriptions/{id}/events for one transcription) and gets transcription.started with the transcriptionId the moment it does. An events socket that falls behind (it reads frames more slowly than they are sent) is closed with code 4004: reconnect. On open it sends the current transcription.started when a transcription is live and nothing else again, so a transcription.ended sent meanwhile is missed: read the transcription (GET /v1/transcriptions/{id}) or, as its owner, the broadcast once after reconnecting.

  2. Subscribe

    Open WS /v1/transcriptions/{id}/subscribe. The owner sends the API key as Authorization: Bearer … (never in the URL); a share link's reader adds shareCode=; a public broadcast's listener sends nothing. lang=es reads it translated (through a share link, the link must allow translation), and VocalStack picks the voice that speaks it (Live translation and spoken translations). The first frame is subscribe.ready: the transcription's state and lastSeq, the cursor the live sequence is at.

  3. Catch up

    Read GET /v1/transcriptions/{id}/transcript (same lang, same credential): every sentence and segment up to the snapshot's own lastSeq. Every durable frame on the socket carries a cursor, gapless per transcription; skip the frames whose cursor is at or below the snapshot's lastSeq (they are in it already) and apply the rest in order. A listener gets a noop frame in place of one withheld from it, so the cursor never skips. If it does jump (a dropped frame, subscribe.gap), read the transcript again with after=<cursor> and carry on from its lastSeq. vs.transcriptions.subscribe in the TypeScript SDK does all of this and hands you the snapshot first. When that second read fails (a rate limit, a network blip) it holds the frames that arrive and asks again, waiting 1, 2, 4 and up to 30 seconds between tries, or as long as a rate limit asks. If the transcript still cannot be read after a minute, or the answer is a refusal, the subscription ends with a closed event whose reason is catch-up failed: subscribe again to start from a fresh snapshot. To come back after any dropped subscription without reading the whole transcript again, pass the old subscription's cursor as since (vs.transcriptions.subscribe(id, { since: sub.cursor })): its first snapshot is then only what changed after that cursor, merged like a gap. A subscriber that falls behind (it reads frames more slowly than they are sent) is closed with code 4004: subscribe again and come back from the last cursor you applied, the same way.

    {"type":"subscribe.ready","transcriptionId":"5c0d…","lastSeq":41,"state":"live","instance":"api-1"}
    {"type":"(snapshot)","lastSeq":42,"text":"Good morning, everyone. Thanks for coming in today."}
    {"type":"transcript.committed","cursor":42,"seq":42,"segment":{"seq":17,"start":5.1,"end":6,"text":"Thanks for coming in today.","speaker":0,"words":[]}}
    {"type":"transcript.committed","cursor":43,"seq":43,"segment":{"seq":18,"start":6.4,"end":8.2,"text":"Let us start with the budget.","speaker":0,"words":[]}}
    {"type":"transcript.translated","cursor":44,"seq":18,"translations":{"es":"Empecemos por el presupuesto."}}
    {"type":"noop","cursor":45,"seq":45}
    {"type":"recording.state","cursor":46,"seq":46,"transcriptionId":"5c0d…","state":"paused"}
  4. Follow it live

    From there, frames arrive as the transcription goes: transcript.committed appends a segment (a subscriber gets no drafts), transcript.sentence replaces a whole sentence by sentenceId, transcript.translated fills a segment's translations, transcript.amended (the engine) and transcript.corrected (a person) rewrite one in place, and recording.state says live, paused, ended, finalized. Change language without reopening: send {"type":"subscribe.update","lang":"fr"} (setLanguage in the SDK), then read the snapshot again in it.

  5. When it ends

    At ended the socket stays open: corrections and the last translations can still arrive until finalized. Close it when you are done. Afterwards, the snapshot is the whole transcript, and GET /v1/transcriptions/{id} says how it ended (state, endReason).

TypeScript SDK

listen.ts

import { VocalStack } from '@vocalstack/js-sdk';

const vs = new VocalStack({ baseUrl: 'https://api.vocalstack.com', apiKey: process.env.VOCALSTACK_API_KEY });
const transcriptionId = process.argv[2]!; // a transcription's id, or a broadcast's currentTranscription.transcriptionId

// The owner, with the key. A share link's reader: new VocalStack({ baseUrl })
// and { shareCode: 'CODE', asOwner: false }; a public broadcast's listener: { asOwner: false }.
const sub = await vs.transcriptions.subscribe(transcriptionId, { lang: 'es' });

// subscribe() resolves once subscribe.ready and the snapshot are in: what
// was said before you came, then only frames past its cursor, gaps healed.
for (const s of sub.snapshot?.sentences ?? []) console.log(s.text, s.translations?.es ?? '');

for await (const ev of sub) {
  if (ev.type !== 'frame') continue;
  const f = ev.frame;
  if (f.type === 'transcript.committed') console.log(f.segment.text);
  if (f.type === 'transcript.translated') console.log(`  es: ${f.translations.es}`);
  if (f.type === 'recording.state') {
    console.log(`[${f.state}]`);
    if (f.state === 'finalized') sub.close();
  }
}

Python SDK

listen.py

import asyncio
import json
import os
import sys

from vocalstack import VocalStack


async def main() -> None:
    async with VocalStack("https://api.vocalstack.com", api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
        transcription_id = sys.argv[1]  # a transcription's id, or a broadcast's current_transcription.transcription_id

        # The owner, with the key. A share link's reader: share_code="CODE", as_owner=False.
        socket = await vs.transcriptions.subscribe(transcription_id, lang="es")
        ready = json.loads(await socket.recv())  # subscribe.ready {lastSeq, state}
        print("state:", ready["state"])

        snapshot = await vs.transcriptions.transcript(transcription_id, lang="es")
        for s in snapshot.sentences:
            print(s.text, (s.translations or {}).get("es", ""))
        cursor = snapshot.last_seq

        async for message in socket:
            if isinstance(message, bytes):
                continue  # live audio, when asked for
            frame = json.loads(message)
            at = frame.get("cursor")
            if at is not None:
                if at <= cursor:
                    continue  # already in the snapshot
                if at > cursor + 1:  # a gap: read what was missed, then go on
                    missed = await vs.transcriptions.transcript(transcription_id, lang="es", after=cursor)
                    for seg in missed.segments:
                        print(seg.text)
                    cursor = max(cursor, missed.last_seq)
                    if at <= cursor:
                        continue
                cursor = at
            if frame["type"] == "transcript.committed":
                print(frame["segment"]["text"], flush=True)
            elif frame["type"] == "transcript.translated":
                print("  es:", frame["translations"].get("es"))
            elif frame["type"] == "recording.state":
                print(f"[{frame['state']}]")
                if frame["state"] == "finalized":
                    await socket.close()


asyncio.run(main())

PHP SDK

listen.php

<?php
// Sockets need phrity/websocket too: composer require phrity/websocket:^3
require 'vendor/autoload.php';

use VocalStack\VocalStack;

$vs = new VocalStack(apiKey: getenv('VOCALSTACK_API_KEY'), baseUrl: 'https://api.vocalstack.com');

$transcriptionId = $argv[1];  // a transcription's id, or a broadcast's currentTranscription

// The owner, with the key. A share link's reader: shareCode: 'CODE', asOwner: false.
$socket = $vs->transcriptions->subscribe($transcriptionId, lang: 'es');
$frames = $socket->messages();  // each text frame, decoded (binary frames are skipped)
$ready = $frames->current();  // subscribe.ready {lastSeq, state}
echo 'state: ', $ready['state'], "\n";

$snapshot = $vs->transcriptions->transcript($transcriptionId, lang: 'es');
foreach ($snapshot['sentences'] as $s) {
    echo $s['text'], ' ', $s['translations']['es'] ?? '', "\n";
}
$cursor = $snapshot['lastSeq'];

for ($frames->next(); $frames->valid(); $frames->next()) {
    $frame = $frames->current();
    $at = $frame['cursor'] ?? null;
    if ($at !== null) {
        if ($at <= $cursor) {
            continue;  // already in the snapshot
        }
        if ($at > $cursor + 1) {  // a gap: read what was missed, then go on
            $missed = $vs->transcriptions->transcript($transcriptionId, after: $cursor, lang: 'es');
            foreach ($missed['segments'] as $seg) {
                echo $seg['text'], "\n";
            }
            $cursor = max($cursor, $missed['lastSeq']);
            if ($at <= $cursor) {
                continue;
            }
        }
        $cursor = $at;
    }
    if ($frame['type'] === 'transcript.committed') {
        echo $frame['segment']['text'], "\n";
    } elseif ($frame['type'] === 'transcript.translated') {
        echo '  es: ', $frame['translations']['es'] ?? '', "\n";
    } elseif ($frame['type'] === 'recording.state') {
        echo "[{$frame['state']}]\n";
        if ($frame['state'] === 'finalized') {
            $socket->close();
        }
    }
}

HTTP + WebSocket

listen-raw.ts

// No SDK, no key: a share link's reader (shareCode), with the built-in
// WebSocket (Node 22 or newer, or a browser).
const API = 'https://api.vocalstack.com';
const [transcriptionId, shareCode] = [process.argv[2]!, process.argv[3]!];
const q = new URLSearchParams({ shareCode, lang: 'es' });

const ws = new WebSocket(`${API.replace(/^http/, 'ws')}/v1/transcriptions/${transcriptionId}/subscribe?${q}`);
let cursor: number | null = null; // null until the snapshot is in
const early: any[] = []; // frames that arrive while it is read

ws.addEventListener('message', async (m: MessageEvent) => {
  if (typeof m.data !== 'string') return;
  const f = JSON.parse(m.data);
  if (f.type === 'subscribe.ready') {
    const r = await fetch(`${API}/v1/transcriptions/${transcriptionId}/transcript?${q}`);
    const snap = (await r.json()) as { lastSeq: number; sentences: { text: string }[] };
    for (const s of snap.sentences) console.log(s.text);
    cursor = snap.lastSeq;
    for (const e of early.splice(0)) apply(e);
    return;
  }
  if (cursor === null) early.push(f);
  else apply(f);
});

function apply(f: any): void {
  if (typeof f.cursor === 'number') {
    if (f.cursor <= cursor!) return; // already in the snapshot
    cursor = f.cursor; // (a jump: read /transcript?after=<cursor> again)
  }
  if (f.type === 'transcript.committed') console.log(f.segment.text);
  if (f.type === 'transcript.translated') console.log(`  es: ${f.translations.es}`);
  if (f.type === 'recording.state') console.log(`[${f.state}]`);
  if (f.type === 'recording.state' && f.state === 'finalized') ws.close();
}