Dev.to AI 🤖 Ai 👁 0 📖 5 min read

Running Whisper in the browser to make subtitles (no server, no upload)

I wanted a subtitle generator where the video never leaves the user's computer. A few years ago that meant shipping audio to a speech API. Today OpenAI's Whisper runs in a normal browser tab through transformers.js and O

I wanted a subtitle generator where the video never leaves the user's computer. A few years ago that meant shipping audio to a speech API. Today OpenAI's Whisper runs in a normal browser tab through transformers.js and ONNX Runtime Web, so the whole thing can be a static page. Here is how I built it, and the parts that took longer than expected.

The pipeline

  1. Decode the audio track in the browser with the Web Audio API.
  2. Mix it down to mono and resample to 16 kHz, which is what Whisper expects.
  3. Run Whisper in a Web Worker and get timestamped segments back.
  4. Turn the chunks into readable subtitle cues (line length, two lines, time per cue).
  5. Write SRT or WebVTT.

1–2. Getting 16 kHz mono audio

decodeAudioData handles most audio and video files the browser can play (MP3, WAV, MP4, WebM…), and gives you one Float32Array per channel at the file's sample rate. Whisper wants a single channel at 16,000 samples per second, so average the channels and resample. Linear interpolation is good enough for speech:

export const SAMPLE_RATE = 16000;

export function toMono16k(channels: Float32Array[], rate: number): Float32Array {
  const n = channels[0]?.length ?? 0;
  const mono = new Float32Array(n);
  for (const ch of channels) for (let i = 0; i < n; i++) mono[i] += ch[i] / channels.length;
  if (rate === SAMPLE_RATE) return mono;
  const out = new Float32Array(Math.floor((n * SAMPLE_RATE) / rate));
  const step = rate / SAMPLE_RATE;
  for (let i = 0; i < out.length; i++) {
    const p = i * step, a = Math.floor(p), b = Math.min(n - 1, a + 1);
    out[i] = mono[a] + (mono[b] - mono[a]) * (p - a);
  }
  return out;
}

An hour of audio at 16 kHz is about 230 MB as 32-bit floats, so keep only this array and let the decoded buffer go.

3. Whisper in a worker

Inference blocks for seconds at a time, so it belongs in a worker. transformers.js gives you a pipeline, and you can pick WebGPU when the browser has it and WebAssembly otherwise:

import { env, pipeline } from '@huggingface/transformers';

env.allowLocalModels = false;
env.useBrowserCache = true; // model files are cached after the first download

const gpu = 'gpu' in navigator && !!(await navigator.gpu.requestAdapter().catch(() => null));
const asr = await pipeline('automatic-speech-recognition', 'onnx-community/whisper-base', {
  device: gpu ? 'webgpu' : 'wasm',
  dtype: gpu ? { encoder_model: 'fp32', decoder_model_merged: 'q4' } : 'q8',
});

const result = await asr(audio, {
  return_timestamps: true,
  chunk_length_s: 30,
  stride_length_s: 5,
  // language: 'english', task: 'transcribe' | 'translate'
});
// result.chunks: [{ text, timestamp: [start, end] }, ...]

Things I learned here:

  • Model size is a real UX decision. The quantized tiny, base and small models are roughly 40, 80 and 250 MB to download. I offer all three as Fast, Balanced and Accurate, and show the size before the download starts.
  • Report download progress. progress_callback fires per file; sum loaded and total across files for one honest progress bar.
  • Your CSP needs to allow the model host. If you serve models from the Hugging Face CDN, connect-src must include https://huggingface.co and its CDN hosts, or the fetch fails with an unhelpful error.
  • Self-host the ONNX Runtime WebAssembly files. Point env.backends.onnx.wasm.wasmPaths at your own copy so you control the version and caching.
  • Catch out-of-memory separately. On low-memory phones the small model can fail to allocate; telling the user to pick a smaller model is much better than a generic error.

4. From chunks to readable subtitles

Whisper's chunks are sentence-ish pieces with start and end times, but they are not subtitles. Broadcast style guides usually ask for at most two lines, about 42 characters per line for landscape video (fewer for vertical), and no cue on screen for more than about seven seconds.

Two details matter:

  • The last chunk often has null as its end time. Close it with the next chunk's start, or the media duration.
  • When a chunk is too long, split it and share its time in proportion to the text, so each piece stays on screen roughly as long as it takes to say.
function wrapLines(text: string, max = 42): string[] {
  const lines: string[] = [];
  let cur = '';
  for (const w of text.split(/\s+/).filter(Boolean)) {
    if (cur && cur.length + 1 + w.length > max) { lines.push(cur); cur = w; }
    else cur = cur ? `${cur} ${w}` : w;
  }
  if (cur) lines.push(cur);
  return lines;
}

function readable(cues: Cue[], max = 42, maxSeconds = 7): Cue[] {
  const out: Cue[] = [];
  for (const c of cues) {
    const lines = wrapLines(c.text, max);
    const groups = Math.max(Math.ceil(lines.length / 2), Math.min(Math.ceil((c.end - c.start) / maxSeconds), lines.length));
    if (groups <= 1) { out.push({ ...c, text: lines.join('\n') }); continue; }
    const per = Math.ceil(lines.length / groups);
    const parts: string[] = [];
    for (let i = 0; i < lines.length; i += per) parts.push(lines.slice(i, i + per).join('\n'));
    const total = parts.reduce((s, p) => s + p.length, 0);
    let t = c.start;
    for (const p of parts) {
      const d = ((c.end - c.start) * p.length) / total;
      out.push({ start: t, end: t + d, text: p });
      t += d;
    }
  }
  return out;
}

A reading-speed check is a cheap extra: characters divided by duration. Netflix's guideline is 17 characters per second for adult content; I flag cues above 20 so the user can shorten or retime them.

5. SRT and WebVTT

Both are plain text. The only differences that bite are the millisecond separator (comma in SRT, dot in VTT) and the WEBVTT header:

const stamp = (s: number, sep: ',' | '.') => {
  const ms = Math.max(0, Math.round(s * 1000));
  const p = (v: number, n = 2) => String(v).padStart(n, '0');
  return `${p(Math.floor(ms / 3600000))}:${p(Math.floor((ms % 3600000) / 60000))}:${p(Math.floor((ms % 60000) / 1000))}${sep}${p(ms % 1000, 3)}`;
};
const toSrt = (cs: Cue[]) => cs.map((c, i) => `${i + 1}\n${stamp(c.start, ',')} --> ${stamp(c.end, ',')}\n${c.text}\n`).join('\n');
const toVtt = (cs: Cue[]) => `WEBVTT\n\n${cs.map((c) => `${stamp(c.start, '.')} --> ${stamp(c.end, '.')}\n${c.text}\n`).join('\n')}`;

Results

Speed depends heavily on the device: WebGPU is much faster than WebAssembly, and the tiny model is several times faster than small. Accuracy on clear speech is very good. Music under the voice and overlapping speakers are where it slips, so an editable cue list before download is not optional.

The nicest part is the privacy story: there is no upload step to explain, because there is no upload.

If you want to try the finished version, it is free at toolstome.com/ai-subtitle-generator. I'd love to hear how it does on your recordings, and what you would change in the cue splitting.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.