Recipes

Transcribe a recording with speaker labels

Turn a long recording into a speaker-labelled transcript and WebVTT captions with a batch job.

You get a transcript, recording.vtt captions, and speaker turns from one complete recording. Install the SDK and set API_URL and API_KEY as in the Quickstart; file size and duration caps are in Limits.

Transcribe and write captions

This uploads recording.wav, waits up to five minutes for the job, prints the transcript, and writes recording.vtt. To change the language or model, see Models and voices.

batch-transcription.ts
import { readFile, writeFile } from 'node:fs/promises';

import {
  BatchDiarization,
  BatchTranscribeClient,
  BatchTranscriptionModel,
  Language,
  Subtitles,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.wav';
  const outputPath = process.argv[3] ?? 'recording.vtt';
  const client = new BatchTranscribeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    api_version: process.env.API_VERSION ?? 'v1',
  });

  try {
    const result = await client.transcribe(
      await readFile(inputPath),
      Language.ArEn,
      {
        asr: BatchTranscriptionModel.BayanArEn,
        diarization: BatchDiarization.On,
        saveResult: true,
        pollInterval: 2,
        timeout: 300,
        onProgress: ({ status }) => console.info('status:', status),
      },
    );

    console.info(result.results?.transcript ?? '');
    await writeFile(outputPath, Subtitles.fromResponse(result).toVtt(), 'utf8');
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

status: queued
status: processing
status: processing
status: done
Yeah, I mean, look, to start with, building infrastructure is not ...

Subtitles builds the captions from the word offsets; call toSrt() (to_srt() in Python) instead of toVtt() for SRT.

Label speakers

With diarization on, the server assigns each word offset a speaker by time. This example groups consecutive words into speaker turns. Labels are opaque strings that only distinguish speakers within one job; see Speaker timelines. Words with no speaker print as UNKNOWN_SPEAKER. Diarization options are in Speaker diarization levels.

batch-speakers.ts
import { readFile } from 'node:fs/promises';

import {
  BatchDiarization,
  BatchTranscribeClient,
  BatchTranscriptionModel,
  Language,
} from '@humain-voice/sdk';

function requiredEnv(name: 'API_KEY' | 'API_URL'): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

async function main(): Promise<void> {
  const inputPath = process.argv[2] ?? 'recording.wav';
  const client = new BatchTranscribeClient({
    api_url: requiredEnv('API_URL'),
    api_key: requiredEnv('API_KEY'),
    api_version: process.env.API_VERSION ?? 'v1',
  });

  try {
    const result = await client.transcribe(await readFile(inputPath), Language.ArEn, {
      asr: BatchTranscriptionModel.BayanArEn,
      diarization: BatchDiarization.On,
      saveResult: true,
      timeout: 300,
      onProgress: ({ status }) => console.info('status:', status),
    });

    const turns: { speaker: string; words: string[] }[] = [];
    for (const offset of result.results?.offsets ?? []) {
      const speaker = offset.speaker ?? 'UNKNOWN_SPEAKER';
      const last = turns[turns.length - 1];
      if (last?.speaker === speaker) last.words.push(offset.word);
      else turns.push({ speaker, words: [offset.word] });
    }
    for (const turn of turns) console.info(`${turn.speaker}: ${turn.words.join(' ')}`);
  } finally {
    await client.close();
  }
}

void main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

Expected output (illustrative):

status: queued
status: processing
status: processing
status: done
SPEAKER_1: Yeah, I mean, look, to start with, building infrastructure is not ...
SPEAKER_2: جلالة الملك فهد بن عبد العزيز ...

Handle failures

ConditionWhat to do
400, 402, 413, or 422No job was created. Fix the request, or add credit for 402; audio over 4 hours returns 422 AUDIO_DURATION_EXCEEDED (Limits).
401Fix API_KEY; see Authentication.
429 or 503 on uploadBack off and resubmit; see Retrying safely.
Upload times out or returns 500, 502, or 504A job may exist. Don't resubmit automatically; see Retries and duplicates.
Job reaches failedThe job failed without a reason. Resubmitting creates a new job; if it fails again, contact support with the job ID.
Job reaches clearedThe result is gone; resubmit. transcribe() keeps polling a cleared job until it times out. Keep saveResult: true (save_result=True) so your own reads don't clear it (Batch is a job).
BatchTranscribeTimeoutErrorRaise timeout (timeout_seconds) for long recordings, or poll err.jobId with getResult(jobId, lang, { saveResult: true }) (get_result(job_id, lang, save_result=True)).

Next steps

On this page