FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Local Whisper Speech Recognition in Web Workers

Move local Whisper inference off the browser UI thread while bounding audio transfer, model startup, long-recording chunks, and memory use.

Freshness: current•14 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

Whisper-in-a-worker places waveform decoding and model inference on a background execution context while the UI owns recording, job IDs, and transcript presentation. The worker holds a single warmed pipeline; each request transfers normalized mono PCM, uses bounded long-form chunks, and returns text with timing metadata. This keeps inference off the UI event loop without eliminating model download, memory, accuracy, or cancellation costs.

Theory

Whisper is an encoder-decoder Transformer, not a direct text function over microphone bytes. Its audio frontend expects a waveform sampled at 16,000 samples per second, then builds an 80-channel log-magnitude Mel spectrogram using 25 ms windows and a 10 ms hop. Transformers.js accepts a Float32Array for automatic speech recognition and runs the task's preprocessing and postprocessing around the model.

A browser may capture at 44.1 or 48 kHz. Decimation must apply a low-pass filter before dropping samples, or high-frequency energy aliases into the speech band. Use a resampler or an OfflineAudioContext configured for the target rate; do not merely pass the original samples while labeling them as 16 kHz. For stereo input, downmix deliberately and test phase cancellation: averaging channels can suppress a voice if the channels contain inverted copies.

The worker should receive normalized mono PCM plus its declared sample rate. Validate the rate, sample format, and duration at the boundary before inference. A Float32Array of samples with no rate metadata is ambiguous, and silently accepting a mismatch changes pitch and timing. Keep timestamps in seconds relative to the original clip so the UI can align words with playback after resampling.

Worker boundary and ownership

A dedicated module worker lets the browser run CPU-heavy preprocessing and decoding independently of the UI script's event loop. It is a responsiveness boundary, not a security boundary: code still runs within the page's origin and can make network requests. If the product promises local processing, keep audio inputs as in-memory arrays and remove any upload or cloud fallback path unless the user explicitly opts into it.

Create one long-lived worker per active transcription session and load the model lazily once. Workers have non-trivial startup and per-instance memory costs, so starting one per utterance multiplies model initialization and may duplicate runtime memory. Transformers.js downloads model assets on the first use and caches them for later calls; version the model revision and serve its weights under the deployment's expected origin if reproducible, offline-capable behavior matters. Browser inference can use WASM or WebGPU, but a GPU backend is not guaranteed across browsers or devices.

Send audio through postMessage with its ArrayBuffer in the transfer list. Transfer avoids structured-cloning the full PCM payload, but ownership moves: the sender's buffer becomes detached and must not be read again. If the application must retain its decoded AudioBuffer, create one deliberate Float32Array copy for the worker and account for that temporary memory. Include a unique job ID in every request and result; a late response from an earlier recording must never replace a newer transcript.

Trade-offs

Whisper was trained on 30-second audio segments, and its long-form strategy advances through bounded windows using timestamps. Transformers.js exposes chunk_length_s and stride_length_s; the stride overlaps adjacent chunks so a word near a boundary is not split into unrelated fragments. The overlap is not free: it reprocesses samples and creates duplicate candidate text that the pipeline must reconcile. Ask for timestamps when the interface needs segment alignment, and inspect chunk boundaries on domain-specific vocabulary rather than assuming concatenated text is exact.

A worker does not make inference real-time. If input arrives faster than the model completes it, an unbounded queue retains waveforms and can exhaust memory. Permit one in-flight transcription and a small bounded queue, then apply an explicit policy: reject, replace the oldest pending job, or stop capture until capacity returns. A cancel message can mark a job's result as stale, but it cannot necessarily interrupt a model call already executing in WASM or WebGPU. For immediate termination, terminate the worker and accept that the next request must reload the runtime and model.

Measure cold model-load time separately from warm inference, and record device, backend, model revision, quantization, clip duration, and word error rate. Transformers.js supports quantized dtypes such as q8, but the available files depend on the model and Whisper encoders are particularly sensitive to quantization choices. Query the model available dtypes, choose q8 only when every required model session offers it, and compare with a higher-precision variant on representative accents, noise, and names before choosing a default. A lower average latency is not a win if boundary omissions or hallucinated text increase.

Capture and decode browser audio
Resample and downmix to mono 16 kHz PCM
Transfer buffer and job ID to a long-lived worker
Run Whisper with bounded 30-second chunks and overlap
Reconcile timestamped text and validate WER before save
Conceptual teaching model synthesized from:radford-whisper-2022,hf-transformers-js-docs,whatwg-web-workers-spec,web-audio-api-spec

Worked sizing example

Consider a 42-second mono recording captured at 48 kHz. It contains 2,016,000 samples before resampling. At Whisper's 16 kHz input rate, the same duration contains 672,000 samples. One float32 worker payload therefore occupies 2,688,000 bytes, or about 2.56 MiB, before feature tensors, model weights, decoder state, and output buffers. Transferring the buffer avoids an additional structured-clone copy, but retaining the original waveform while making a transferable copy still raises the peak by roughly another 2.56 MiB.

The sample count follows duration times the target sample rate:

NPCM=Taudio×fsampleN_{\text{PCM}} = T_{\text{audio}} \times f_{\text{sample}}

Here, T_audio is elapsed time in seconds, f_sample is samples per second, and N_PCM is a count of float samples. For this clip, the 16 kHz representation has 42 s × 16,000 samples/s = 672,000 samples. A 30-second chunk with a 5-second stride overlap bounds each model window and revisits boundary audio; the right choice still depends on device memory and measured boundary accuracy.

Track recognition error with the standard word error rate:

WER⁡=S+D+INref\operatorname{WER} = \frac{S + D + I}{N_{\text{ref}}}

S, D, and I count substitutions, deletions, and insertions; N_ref is the number of words in the reference transcript. WER is dimensionless. Report it alongside time-to-first-result and peak memory, because a tiny model can feel fast while producing poor names or dropping words at chunk joins.

Decision scenario

A browser speech service must add long-form meeting transcription without blocking the recording controls or retaining unbounded audio. Run one warmed worker, cap each job at a measured duration, keep only a small pending queue, and tag every result with a job ID. Compare a 30-second window with 5-second overlap against a shorter-window configuration on annotated boundary cases; report WER, peak memory, and time to first transcript. Show partial output as provisional, and discard late results after the user starts a newer recording.

Implementation pattern

The producer below resamples or prepares mono audio before this call. slice() creates one owned copy; transferring its buffer prevents the worker message from cloning every sample again.

typescript
const asrWorker = new Worker(new URL("./asr.worker.js", import.meta.url), { type: "module" });
​
function submitPcm16k(jobId: string, pcm16k: Float32Array): void {
const ownedPcm = pcm16k.slice();
asrWorker.postMessage(
{ type: "transcribe", jobId, sampleRate: 16_000, pcmBuffer: ownedPcm.buffer },
[ownedPcm.buffer],
);
}
​
function cancelTranscription(jobId: string): void {
asrWorker.postMessage({ type: "cancel", jobId });
}

A module worker keeps a single pipeline and serializes work. It rejects malformed or oversized audio, returns timing chunks, and suppresses a result after cancellation rather than pretending the running model can be interrupted.

javascript
import { ModelRegistry, pipeline } from "@huggingface/transformers";
​
const modelId = "Xenova/whisper-tiny.en";
let pipelinePromise;
let busy = false;
const cancelled = new Set();
​
function getTranscriber() {
if (!pipelinePromise) {
pipelinePromise = (async () => {
const dtypes = await ModelRegistry.get_available_dtypes(modelId);
const options = dtypes.includes("q8") ? { dtype: "q8" } : {};
return pipeline("automatic-speech-recognition", modelId, options);
})().catch((error) => {
pipelinePromise = undefined;
throw error;
});
}
return pipelinePromise;
}
​
self.addEventListener("message", async ({ data }) => {
if (data.type === "cancel") {
cancelled.add(data.jobId);
return;
}
if (data.type !== "transcribe") return;
const { jobId, sampleRate, pcmBuffer } = data;
if (busy) {
self.postMessage({ type: "busy", jobId });
return;
}
busy = true;
try {
if (!jobId || sampleRate !== 16_000 || !(pcmBuffer instanceof ArrayBuffer)) throw new Error("Expected a job ID and transferred 16 kHz PCM buffer");
if (pcmBuffer.byteLength % 4 !== 0 || pcmBuffer.byteLength > 16_000 * 60 * 4) throw new Error("PCM buffer is malformed or exceeds the 60-second limit");
const pcm = new Float32Array(pcmBuffer);
if (pcm.length === 0) throw new Error("Audio is empty");
const transcriber = await getTranscriber();
const output = await transcriber(pcm, { chunk_length_s: 30, stride_length_s: 5, return_timestamps: true });
const type = cancelled.has(jobId) ? "cancelled" : "result";
self.postMessage({ type, jobId, text: type === "result" ? output.text : "", chunks: type === "result" ? output.chunks ?? [] : [] });
} catch (error) {
self.postMessage({ type: "error", jobId, message: error instanceof Error ? error.message : String(error) });
} finally {
cancelled.delete(jobId);
busy = false;
}
});

Failure modes and misconceptions

FailureSymptomProduction response
Wrong sample-rate metadataSpeech is too fast, slow, or unintelligibleResample the waveform and validate the numeric rate at the worker boundary
Chunk seam or timestamp driftRepeated or missing words around window joinsKeep overlap, request timestamps, and test long recordings with annotated boundary cases
Cold-start memory spikeTab reloads or inference fails before returning textLoad on demand, cap clip duration, measure peak memory, and offer a server path only with consent
Stale or canceled job completes lateAn old transcript overwrites the current recordingMatch every reply to a job ID and discard canceled or superseded results
Unsupported acceleration backendWebGPU initialization fails on a deviceFall back to WASM when supported and benchmark that path independently

No browser worker can guarantee identical latency or accuracy across device classes. Keep an explicit maximum clip length, surface model download progress, persist only the transcript the user chooses to save, and make local versus remote processing visible in the product contract.

Learning outcomes

  • Explain how browser audio becomes a correctly sampled Whisper waveform and how to transfer it to a worker.
  • Design bounded, job-ID-based worker execution with chunk overlap, cancellation, and backpressure limits.
  • Compare local model accuracy, startup time, peak memory, and UI responsiveness on target devices.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next