How higuma/web-audio-recorder-js works
Project Type and Purpose
• This is a client-side JavaScript library (an open-source tool) that records audio via the Web Audio API and encodes it into WAV, Ogg, or MP3 formats using Web Workers.
Main Components
a. Host Application (Web Page)
• Loads WebAudioRecorder.js on the main browser thread.
• Provides an AudioNode (e.g., microphone input via getUserMedia).
• Receives final Blob (audio file) via event callbacks.
b. WebAudioRecorder Core (Main Script)
• API surface: constructor, setEncoding, setOptions, start/stop/cancel, event handlers.
• Orchestrates recording and worker management.
• Uses Web Audio API (ScriptProcessorNode or AudioWorklet) under the hood to capture PCM buffers.
c. Worker Manager
• Dynamically loads one of three worker scripts (WebAudioRecorderWav.js, WebAudioRecorderOgg.js, WebAudioRecorderMp3.js) based on chosen encoding.
• Passes raw PCM buffers to the worker via postMessage.
• Receives progress updates and final ArrayBuffer/Blob from worker.
d. Encoder Worker (for each format)
• Contains bundled encoder library (e.g., WavAudioEncoder.js, OggVorbisEncoder.js, Mp3LameEncoder.js).
• Performs CPU-intensive encoding off the main thread.
• Uses a memory initializer file (*.mem) for WASM/emulation if needed.
• Posts state messages: “loaded,” “progress,” “complete,” “error.”
e. External Encoder Libraries
• Imported by worker scripts, they implement the actual format encoders.
• Hosted in lib/, also available in lib-minified/.
f. Blob Output
• Worker returns an encoded Blob to the main script.
• Main script triggers onComplete(recorder, blob) so host app can save/play the file.
Relationships & Data Flow
• Host App → Core Script: instantiate recorder, pass AudioNode & config.
• Core Script → Web Audio API: subscribe to PCM data.
• Core Script → Worker Manager: load appropriate worker (workerDir + worker script).
• Core Script → Worker Thread: stream PCM chunks via postMessage.
• Worker Thread → Core Script: send back encoding progress or final Blob.
• Core Script → Host App: invoke event handlers (onComplete, onError, onEncodingProgress).
Architectural Patterns & Principles
• Worker-Based Concurrency: Offload CPU-heavy encoding to Web Workers.
• Event-Driven: Use event callbacks for lifecycle (loading, progress, complete, error).
• Pluggable Encoders: Strategy pattern—swap in WAV/Ogg/MP3 encoding logic.
• Separation of Concerns: Main script concerns itself only with orchestration; workers handle encoding.
Technologies & Libraries
• Web Audio API (AudioNode, ScriptProcessorNode / AudioWorklet)
• Web Workers (postMessage, worker.terminate)
• Encoder libraries (WavAudioEncoder.js, OggVorbisEncoder.js, Mp3LameEncoder.js)
• Blob API for output