Skip to content

WebAssembly Guide: Audio Analysis in the Browser ​

libsonare can be compiled to WebAssembly for audio analysis directly in web browsers. The key rule: its APIs work on decoded audio samples (a mono Float32Array of numbers), not on a raw .mp3/.wav file. You get those samples either by decoding the file yourself with the Web Audio API or another JavaScript decoder, or by handing the encoded bytes to the Audio.fromMemory* helpers, which decode for you. The table below shows the full path.

Use this page when you are building a browser app. If you are writing a Python script, terminal batch job, or native desktop tool, start with Getting Started and choose another runtime.

This page covers setup, the one-shot browser APIs, mastering, Web Worker integration, performance tuning, and a React example. For live streaming analysis, inverse reconstruction, and the realtime voice changer, see WASM Streaming and Realtime.

Browser Mental Model ​

From a file to a libsonare call
decodepick a channelafter init()File or bytesDecoded PCMSamples + sampleRatelibsonare call
The package never reads compressed file bytes: decode first, then pass one channel of samples with the rate they were decoded at.
StepWhat happens
1. Load a fileUse fetch, an <input type="file">, drag-and-drop, or another browser source
2. Decode audioUse Audio.fromMemory(...), Audio.fromMemoryWithBrowserFallback(...), AudioContext.decodeAudioData(...), or your own decoder
3. Choose samplesPass one mono channel, downmix stereo yourself, or call stereo APIs where available
4. Call libsonarePass samples plus sampleRate to analysis, editing, mastering, or mixing APIs

The most common beginner mistake is passing an MP3 ArrayBuffer directly to an analysis function. Decode it first; libsonare's browser package works on PCM samples, not compressed file bytes.

Three quick sanity checks catch most setup problems:

  • await init() has completed before any DSP call.
  • The value passed as sampleRate is the rate of the decoded samples, usually audioBuffer.sampleRate.
  • The sample array is PCM audio (Float32Array), not encoded file bytes.
What are Float32Array, PCM, mono, and downmixing?
  • PCM samples are the raw, uncompressed waveform: a long list of amplitude numbers. An MP3/WAV file is compressed or wrapped bytes; decoding turns it into PCM.
  • Float32Array is the JavaScript typed array the Web Audio API uses to hold those samples as 32-bit floats (normally in the −1…1 range), one number per sample. libsonare's browser API takes this directly.
  • Mono / downmixing: mono is a single channel. Stereo audio has separate left and right channels; downmixing combines them into one (typically by averaging) so you can pass a single channel to a mono API.

What You Will Learn ​

By the end of this page you should be able to:

  • install and initialize the WASM package correctly;
  • decode browser files into PCM and pass the right channel/sample-rate pair to libsonare;
  • choose between one-shot functions, Audio, StreamAnalyzer, StreamingMasteringChain, Mixer, and RealtimeEngine;
  • understand the bundle-size and Worker/AudioWorklet tradeoffs before shipping a browser app.

Installation ​

npm/yarn ​

bash
npm install @libraz/libsonare
bash
yarn add @libraz/libsonare
bash
pnpm add @libraz/libsonare

CDN ​

html
<script type="module">
  import { init, detectBpm } from 'https://unpkg.com/@libraz/libsonare';
</script>

Basic Usage ​

typescript
import { init, detectBpm, detectKey, analyze } from '@libraz/libsonare';

async function analyzeAudio() {
  // Initialize WASM module
  await init();

  // Get audio data from AudioContext
  const audioCtx = new AudioContext();
  const response = await fetch('music.mp3');
  const arrayBuffer = await response.arrayBuffer();
  const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);

  // Get one mono channel. Downmix explicitly if you need both stereo channels.
  const samples = audioBuffer.getChannelData(0);
  const sampleRate = audioBuffer.sampleRate;

  // Detect BPM
  const bpm = detectBpm({ samples, sampleRate });
  console.log(`BPM: ${bpm}`);

  // Detect key
  const key = detectKey({ samples, sampleRate });
  console.log(`Key: ${key.name}`);  // "C major"

  // All-in-one analysis
  const result = analyze({ samples, sampleRate });
  console.log(result);
}
CLI equivalents

The same one-file checks from the sonare command line (not available in the browser):

bash
sonare bpm music.mp3
sonare key music.mp3
sonare analyze music.mp3 --json

The demo below is the same data flow in visual form: decoded samples go in, a time/frequency view comes out. If your browser page can render this kind of result, the WASM package, initialization, decoding, and sample-rate plumbing are all connected.

STFT · SPECTRALIDLE
STFT — seeing time and frequency at once

A tone gliding from 400 Hz to 1 kHz, with four clicks. Each column is one short-time spectrum; brighter means more energy. Change nFft: at 256 the clicks are thin lines and the tone is a band about 170 Hz wide; at 4096 the tone is a line about 20 Hz wide and each click smears across about 90 ms (all widths measured 6 dB down from the peak).

nFft (window)

The browser build also exposes the librosa-parity helper set, so existing librosa recipes port over. Helpers and Conversions lists the functions by intent, and librosa Compatibility maps them to their librosa names.

Browser Mixing ​

mixStereo(...) renders stems in one call, and a persistent Mixer built from scene JSON keeps buses, sends, insert automation and strip meters across blocks. Both run in the browser exactly as in any other runtime: the calls are on Audio and Mixing API, and Mixing Engine is the walkthrough.

Audio Class ​

Audio wraps decoded samples and their sample rate, so analysis, effects and feature calls do not repeat them. In the browser the usual source is a decoded AudioBuffer:

typescript
const audio = Audio.fromBuffer(audioBuffer.getChannelData(0), audioBuffer.sampleRate);
const bpm = audio.detectBpm();

The Audio class reference lists the instance methods.

Browser Mastering ​

The /mastering demo uses the same WASM package described here. Audio decoding happens in the browser, mastering work runs in a Web Worker, and the rendered WAV plus JSON report are created locally. The Mastering reference covers masterAudio, the named processors and the assistant calls; Mastering Demo Implementation covers how the page is built. Background: Browser Local Processing, The Mastering Chain and Stereo, Limiter, and Loudness Controls.

File Input ​

Most WASM APIs take decoded PCM samples. For encoded bytes, use Audio.fromMemory(...) for WAV/MP3 or Audio.fromMemoryWithBrowserFallback(...) to try the native decoder first and then use AudioContext.decodeAudioData() for browser-supported formats such as AAC, OGG, and FLAC.

typescript
async function analyzeFile(file: File) {
  await init();
  const audioCtx = new AudioContext();

  const arrayBuffer = await file.arrayBuffer();
  const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
  const samples = audioBuffer.getChannelData(0);

  return analyze({ samples, sampleRate: audioBuffer.sampleRate });
}

// Usage with file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const result = await analyzeFile(file);
  console.log(`BPM: ${result.bpm}`);
});

Keeping Every Channel ​

Audio.fromMemory(...) folds a multichannel file to mono as it decodes. To keep the channels, decode with decodeChannels:

FunctionKeeps channelsDecoderReturns
Audio.fromMemoryNo, folds to monoWAV/MP3 in WASMAudio
Audio.fromMemoryWithBrowserFallbackNo, folds to monoWASM, then decodeAudioDataPromise<Audio>
decodeChannelsYesWAV/MP3 in WASM{ sampleRate, channels }
decodeChannelsWithBrowserFallback(bytes, options?)YesWASM, then decodeAudioData (AAC, OGG, FLAC)Promise<{ sampleRate, channels }>
downmix(channels, targetLayout, options?)NarrowsNoneFloat32Array[]

channels holds one Float32Array per source channel in the source's own order (5.1 is L R C LFE Ls Rs). downmix folds them to 'mono', 'stereo', '5.1' or '7.1' with the ITU-R BS.775 rule; its options, the unnormalized-fold caveat and the refusals are on Audio and Mixing API.

Storing A Clip In OPFS ​

writeOpfsClip(path, channels) writes planar Float32Array channels into the Origin Private File System as headerless little-endian interleaved float32, the layout the OPFS clip page readers already read. importOpfsClip(path, source) accepts an ArrayBuffer, a Blob, or an AudioBuffer, keeps every channel, and returns the source sampleRate without resampling. Both run in the OPFS worker, and writing to a path an open page provider is reading throws InvalidState. See Realtime and Streaming for paging such a clip into the engine.

Progress Reporting ​

typescript
import { init, analyze } from '@libraz/libsonare';

await init();

const result = analyze({
  samples,
  sampleRate,
  onProgress: (progress, stage) => {
    const percent = Math.round(progress * 100);
    console.log(`${stage}: ${percent}%`);

    // Update UI
    progressBar.style.width = `${percent}%`;
    statusText.textContent = stage;
  },
});

Cancellation ​

Long-running offline analysis and mastering calls take a cancel callback, polled at the same boundaries onProgress reports, so a user who loads the wrong file does not have to wait out the render. Returning true aborts the call with SonareError code 8 (Cancelled) and leaves its outputs unallocated: there is no partial result to read, so treat the throw as "nothing happened" rather than "half a master". Canceling a long call has the full example.

Stereo to Mono Conversion ​

typescript
async function getMonoSamples(audioBuffer: AudioBuffer): Promise<Float32Array> {
  if (audioBuffer.numberOfChannels === 1) {
    return audioBuffer.getChannelData(0);
  }

  // Mix stereo to mono. For 5.1 / 7.1 sources use decodeChannels() and downmix().
  const left = audioBuffer.getChannelData(0);
  const right = audioBuffer.getChannelData(1);
  const mono = new Float32Array(left.length);
  for (let i = 0; i < left.length; i++) mono[i] = (left[i] + right[i]) / 2;
  return mono;
}

Web Worker Usage ​

Offline analysis and mastering are synchronous and block the thread they run on. The package ships a Worker client so the common case needs no worker file of your own. Import OfflineWorkerClient from the main entry point @libraz/libsonare (the /worker subpath is the worker-side entry and exports installOfflineWorkerEndpoint):

typescript
import { OfflineWorkerClient } from '@libraz/libsonare';

const client = new OfflineWorkerClient();

const controller = new AbortController();
cancelButton.onclick = () => controller.abort();

const result = await client.analyze(
  { samples, sampleRate, onProgress: (progress, stage) => updateUi(progress, stage) },
  { signal: controller.signal },
);
await client.destroy();

analyze, detectBpm, detectKey, detectChords, masterAudio, and masterAudioStereo are available. Each takes the same request object as the main-thread function and returns a Promise. onProgress stays on the calling thread and receives (progress, stage) as the worker reports it; the synchronous cancel predicate is not accepted, because a function cannot cross the thread (a function-valued request field rejects with TypeError), so cancel with an AbortSignal instead.

Client options ​

OptionMeaning
workerReuse a Worker the host owns instead of creating one. A browser Worker or a Node worker_threads Worker
workerUrlURL of the Worker entry, resolved against the client module's URL. Defaults to the published worker.js next to the client
workerFactory(url) => worker: creates the dedicated Worker, for tests or custom construction
terminateWorkerOnDestroyTerminate a Worker you supplied through worker when destroy() runs (a Worker the client created is always terminated)

Each call also takes { copy?, signal? } as its second argument: copy keeps your input arrays (see the warning below), and signal is an AbortSignal that cancels the call at the core's next native progress boundary.

If your bundler moves or rewrites the package files, pass a workerUrl that resolves to the published worker.js (the file behind @libraz/libsonare/worker).

Cancellation and destruction ​

Aborting the signal rejects the call with a SonareError whose code is 8 (Cancelled) and whose cause is signal.reason; a signal that is already aborted rejects without dispatching work. destroy() rejects outstanding work with InvalidState, releases the Worker, and returns a Promise that resolves once the Worker has terminated; a second destroy() returns the same promise, and a call made after it rejects with SonareError InvalidState. The client also implements [Symbol.asyncDispose](), so await using client = new OfflineWorkerClient() releases it at the end of the scope. TypeError and RangeError raised inside the Worker are rebuilt as the same classes on the calling thread, and a SonareError keeps its code. A request whose message could not be posted is settled with an error instead of staying pending. A method called on a deleted WASM handle raises InvalidState.

Inputs are transferred, not copied

Float32Array inputs are transferred to the Worker by default, so the buffer becomes detached on the calling thread and reading it afterwards yields an empty array. Pass { copy: true } when you still need the samples, for drawing a waveform, say. Prompt cancellation of an already-running native call needs cross-origin isolation (the client uses a SharedArrayBuffer flag); without it, cancellation still lands, at the next task boundary.

Project, Mixer, and the realtime classes are deliberately absent from the client: their native handles belong to one JavaScript realm and cannot be moved across threads. VocalEditWorkerClient (behind @libraz/libsonare/vocal-edit-worker) is the equivalent for vocal-edit drafts and render jobs.

Writing your own worker ​

If you need an operation the client does not expose, the ordinary pattern still works: import the main entry inside a worker of your own.

worker.ts:

typescript
import { init, analyze } from '@libraz/libsonare';

const ready = init();

self.onmessage = async (e: MessageEvent) => {
  const { samples, sampleRate } = e.data;
  try {
    await ready;
    self.postMessage({ success: true, result: analyze({ samples, sampleRate }) });
  } catch (error) {
    self.postMessage({ success: false, error: error.message });
  }
};

main.ts:

typescript
import type { AnalysisResult } from '@libraz/libsonare';

const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });

function analyzeInWorker(samples: Float32Array, sampleRate: number): Promise<AnalysisResult> {
  return new Promise((resolve, reject) => {
    worker.onmessage = (e) =>
      e.data.success ? resolve(e.data.result) : reject(new Error(e.data.error));
    worker.postMessage({ samples, sampleRate });
  });
}

Performance Tips ​

Downsampling ​

For BPM detection, 22050 Hz is sufficient:

typescript
import { resample, detectBpm } from '@libraz/libsonare';

// Downsample for faster analysis
const downsampled = resample({ samples, sampleRate: 48000, targetSampleRate: 22050 });
const bpm = detectBpm({ samples: downsampled, sampleRate: 22050 });

Analyze Segments ​

For long files, analyze only relevant sections:

typescript
function analyzeSegment(
  samples: Float32Array,
  sampleRate: number,
  startSec: number,
  endSec: number
) {
  const start = Math.floor(startSec * sampleRate);
  const end = Math.floor(endSec * sampleRate);
  const segment = samples.slice(start, end);

  return analyze({ samples: segment, sampleRate });
}

// Analyze only chorus (60-90 seconds)
const result = analyzeSegment(samples, sampleRate, 60, 90);

The same slicing, looped over fixed chunks (for example 60 seconds at a time), keeps memory use bounded for very long files.

React Example ​

Run the analysis through the Worker client so the page keeps painting while the native call runs. Create the client in an effect and destroy it on unmount.

tsx
import { useEffect, useRef, useState } from 'react';
import { ErrorCode, isSonareError, OfflineWorkerClient, type AnalysisResult } from '@libraz/libsonare';

function AudioAnalyzer() {
  const [progress, setProgress] = useState(0);
  const [stage, setStage] = useState('');
  const [result, setResult] = useState<AnalysisResult | null>(null);
  const client = useRef<OfflineWorkerClient | null>(null);
  const controller = useRef<AbortController | null>(null);

  useEffect(() => {
    client.current = new OfflineWorkerClient();
    return () => { void client.current?.destroy(); };
  }, []);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !client.current) return;

    const audioCtx = new AudioContext();
    const arrayBuffer = await file.arrayBuffer();
    const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
    const samples = audioBuffer.getChannelData(0);

    controller.current = new AbortController();
    try {
      setResult(
        await client.current.analyze(
          {
            samples,
            sampleRate: audioBuffer.sampleRate,
            onProgress: (p, s) => { setProgress(p); setStage(s); },
          },
          { signal: controller.current.signal },
        ),
      );
    } catch (error) {
      if (!(isSonareError(error) && error.code === ErrorCode.Cancelled)) throw error;
    }
  };

  return (
    <div>
      <input type="file" accept="audio/*" onChange={handleFileChange} />

      {stage && (
        <div>
          {stage}: <progress value={progress} max={1} />
          <button onClick={() => controller.current?.abort()}>Cancel</button>
        </div>
      )}

      {result && <p>BPM: {result.bpm.toFixed(1)}, key: {result.key.name}</p>}
    </div>
  );
}

A canceled call rejects with SonareError code 8 (Cancelled); the catch around await client.current.analyze(...) treats a cancel as a normal outcome.

Browser Compatibility ​

Runs in Chrome 93, Firefox 92 and Safari 16.4 or later, and in Node.js 22.12 or later. Edge follows Chrome's version numbers, so its floor is also 93.

Requirements: WebAssembly SIMD, BigInt, and the Web Audio API. The JavaScript bundles target ECMAScript 2020.

Package Artifacts ​

The published package ships a few coordinated pieces:

  • Main module: sonare.js plus sonare.wasm, the Emscripten build behind every analysis, mastering, mixing, and editing API.
  • Main API entry: the package index (index.js / index.d.ts) is the tsup bundle behind import ... from '@libraz/libsonare'; it exposes the all-in-one analysis, mastering, mixing, and editing API.
  • AudioWorklet entry: worklet.js / worklet.d.ts, a separate, self-contained tsup bundle (no code-splitting, so it is fully portable into an AudioWorkletGlobalScope); it carries the SonareEngine API, the worklet processor classes and their registration helpers, SonareStreamAnalyzerNode (live analysis of an audio-graph branch), and the ring-buffer protocol (with SONARE_METER_RING_PROTOCOL_VERSION; set levels through SonareEngine.setStripFaderDb and its siblings), and re-exports init and isInitialized from the main entry. Within one realm the two entries share one module state, so after init() through either entry the worklet entry's classes, SonareEngine.create among them, read the engine ABI themselves. The playback and mixer processors take the compiled module as wasmBinary in their processor options and initialize it themselves when the worklet realm has none, posting ready once it is up. The voice-changer, mixer, engine and playback processors run at the AudioWorkletGlobalScope sample rate: a differing sampleRate option is refused with a RangeError, and outside a worklet scope the option is required. Create each shared-memory ring with its createSonare*RingBuffer helper and load the worklet and main-thread code from the same package version (the meter ring is protocol 3, the spectrum, scope and telemetry rings protocol 1); a hand-sized buffer is refused when the processor is constructed. A failure raised on the audio thread keeps its class and any SonareError code when it reaches the main thread.
  • Analysis-only module: sonare-analysis.js / sonare-analysis.wasm behind the @libraz/libsonare/analysis entry (the raw asset is @libraz/libsonare/wasm/analysis), compiled without the mastering, mixing, realtime, and project bindings. CI records its size in a report, but size growth alone does not fail the build.
  • Offline Worker entry: worker.js behind @libraz/libsonare/worker, the Worker side of OfflineWorkerClient.
  • Vocal-edit Worker entry: vocal_edit_worker.js behind @libraz/libsonare/vocal-edit-worker, the Worker side of VocalEditWorkerClient.
  • Voice-changer JSON Schemas: both preset schemas ship in the package under schemas/, so a host can validate a preset document without fetching anything.

Instantiating The Module Yourself ​

sonare.js / sonare.wasm are the Emscripten module the package wraps, and almost no application needs to touch them directly: importing from @libraz/libsonare instantiates the module, keeps one instance per realm, and is the supported entry point. If you do instantiate the module yourself (a custom loader, a non-standard bundler target, a host that manages its own heap), one input shape is worth knowing about.

The mastering-chain binding takes the flattened envelope only

The module's mastering-chain entry accepts exactly one configuration shape: the flattened parameter envelope that the core's own parameter parser reads. Hand it a nested configuration object instead and the call is refused by name: it reports the configuration it cannot read rather than applying the part of it that it recognizes and dropping the rest.

This does not affect the npm package. masterAudio flattens a nested MasteringChainConfig (repair stages, denoise settings and all) before anything crosses into the module, so code that imports from @libraz/libsonare passes nested configs exactly as the JavaScript API describes and is unaffected. Only a caller who instantiates the module directly and passes a nested object straight into the binding meets this, and what they get is a clear error instead of a partly applied chain.

Bundle Size ​

The size table covers the main module and the main API entry. The analysis-only module, the realtime runtime, and the worklet bundle are separate artifacts and are not listed here; the analysis module is substantially smaller than sonare.wasm because it leaves the mastering, mixing, realtime, and project surfaces out.

FileSizeGzipped
sonare.js~82 KB~15 KB
index.js~847 KB~181 KB
sonare.wasm~7,574 KB~2,855 KB
Total~8,503 KB~3,051 KB

Troubleshooting ​

AudioContext Not Allowed ​

Modern browsers require user interaction before creating AudioContext:

typescript
document.addEventListener('click', async () => {
  const audioCtx = new AudioContext();
  await audioCtx.resume();
});

Cross-Origin Issues ​

When loading audio from other domains:

typescript
const response = await fetch(url, {
  mode: 'cors',
  credentials: 'omit'
});

Which Error You Get ​

Failures from the library are a structured SonareError with a numeric code and codeName; an argument that is refused (an out-of-range value, an unknown id or name, a wrong type) is a plain RangeError or TypeError, so a SonareError handler does not catch it; a failure caused by earlier configuration or a released object is a coded InvalidState. Error Handling has the class table, the failure-to-class table, and an example that handles all three. The error contract lists the same failures on every other binding. A .wasm built from a different tree than the JavaScript throws AbiMismatch (code 10) from init(); Installation covers the usual causes.