Skip to content

Build In-Browser Captions With transformers.js and Whisper (Developer Walkthrough)

A minimal pipeline for speech-to-text in the browser: load Whisper with transformers.js, choose WebGPU or WASM, decode audio, get timestamps and write SRT.

Try it now: AI Subtitle Generator — timed subtitles from speech in 20 languages, processed in your browser.

transformers.js runs Hugging Face models in the browser through ONNX Runtime, and automatic speech recognition is one of its supported tasks. That is enough to build a small caption generator. This walkthrough uses only public APIs; it is not GenKit Lab's source code.

What you will build

A page that takes an audio file, runs Whisper on the user's device and prints timed segments you can turn into an SRT.

1. Install

bash
npm install @huggingface/transformers

2. Create the pipeline (in a worker)

Model loading and inference block the thread they run on, so put them in a Web Worker.

js
// worker.js
import { pipeline } from "@huggingface/transformers";

let transcriber;

self.onmessage = async ({ data }) => {
  if (!transcriber) {
    transcriber = await pipeline(
      "automatic-speech-recognition",
      "Xenova/whisper-tiny.en",        // small English-only model, for a first test
      { device: "webgpu", dtype: "fp32" }   // omit device to use WASM on CPU
    );
  }
  const out = await transcriber(data.audio, {
    return_timestamps: true,
    chunk_length_s: 30,
    stride_length_s: 5,
  });
  self.postMessage(out.chunks);          // [{ timestamp: [start, end], text }, ...]
};

Notes from the docs:

  • By default models run on the CPU through WASM. Setting device: "webgpu" uses the GPU, and the docs warn WebGPU is still experimental in many browsers, so feature-detect (navigator.gpu) and fall back.
  • dtype selects precision: fp32 (the default for WebGPU), fp16, q8 (the default for WASM) and q4. Available choices vary by model.
  • Pick a multilingual model (not a .en one) if you need languages other than English; see Whisper model sizes.

3. Decode audio to what Whisper expects

Whisper takes 16 kHz mono floating-point samples. In the browser:

js
async function fileToFloat32(file) {
  const ctx = new AudioContext({ sampleRate: 16000 });
  const buf = await ctx.decodeAudioData(await file.arrayBuffer());
  return buf.getChannelData(0);          // first channel; mix down if you need both
}

For big videos, decoding the whole file is memory-hungry; stream-decode only the audio window you need if your target browsers support WebCodecs.

4. Turn chunks into SRT

Each chunk has timestamp: [start, end] in seconds. Convert to HH:MM:SS,mmm:

js
const pad = (n, w) => String(n).padStart(w, "0");
function stamp(sec) {
  const ms = Math.round(sec * 1000);
  return `${pad(Math.floor(ms / 3600000), 2)}:${pad(Math.floor(ms / 60000) % 60, 2)}:` +
         `${pad(Math.floor(ms / 1000) % 60, 2)},${pad(ms % 1000, 3)}`;
}
const toSrt = (chunks) => chunks.map((c, i) =>
  `${i + 1}\n${stamp(c.timestamp[0])} --> ${stamp(c.timestamp[1] ?? c.timestamp[0] + 2)}\n${c.text.trim()}`
).join("\n\n") + "\n";

The last chunk can have a null end time, hence the fallback. For parsing and validating the result, see SRT and WebVTT helpers.

5. Practical advice

ConcernAdvice
First load is slowModels are downloaded; show progress and let the browser cache them
MemoryUse the smallest model that meets your quality bar; quantised dtypes shrink size
Browser supportWebGPU has limited availability (MDN); always provide the WASM path
LanguageSet the language explicitly when you know it rather than relying on detection
PrivacyAudio stays in the page; the model download is the network traffic

What this does not give you

A production tool also needs a caption editor, line-length rules, export formats, model-selection logic per device and a lot of testing. That is the gap between this sketch and a finished tool such as the subtitle generator; the user-level view is in how browser captioning works.

Sources

Last updated