JavaScript/TypeScript API Reference
The npm package @libraz/libsonare is the WebAssembly build of the engine: analysis, mastering, mixing, editing DSP, and a realtime engine, all running in the browser. This page covers install, init(), your first call, and the conventions every function shares (request objects, errors, sample rates). Per-subject reference pages follow from the list at the end.
Overview
Most functions take decoded PCM, not a file: a Float32Array of samples plus the sampleRate it was decoded at. To get from encoded bytes to samples, decode with the Web Audio API (AudioContext.decodeAudioData) or use the Audio.fromMemory* factories, which decode WAV/MP3 with the bundled WASM decoder and AAC/OGG/FLAC through the browser when needed. decodeChannelsWithBrowserFallback(bytes, options?) takes the same path but keeps every channel instead of folding to mono; see Keeping Every Channel.
Start from the task, not from the function list:
| You need | Start with | Why |
|---|---|---|
| One tempo, key, or beat value | detectBpm, detectKey, detectBeats | Direct answers without building the all-in-one analysis object |
| Metadata for a whole song | analyze (with onProgress for a progress bar), or a focused analyze* helper | analyze gives the common summary; the helpers expose more detail |
| Spectral features for ML or visualization | melSpectrogram, chroma, mfcc | Matrix outputs |
| A live visualizer or an updating BPM/key/chord UI | StreamAnalyzer | Processes small blocks; the UI reads the newest frames |
| Remixing, practice tools, region repair | hpss, timeStretch, pitchShift, spectralEdit | Audio effects |
| Vocal tuning, note edits, pitch or formant changes | pitchCorrectToMidi, noteStretch, voiceChange, StreamingRetune, RealtimeVoiceChanger | Editing DSP changes the signal rather than analyzing it |
| Loudness targets, true-peak limiting, delivery preview | masterAudio, masterAudioStereo, StreamingMasteringChain | Presets first, named processors when you need control |
| Stem balance, sends, buses, or meters | mixStereo or Mixer | One-shot mix first; a persistent scene mixer when routing matters |
| Room decay, clarity, equivalent-room estimates, generated room character | analyzeImpulseResponse, detectAcoustic, estimateRoom, synthesizeRir, roomMorph, roomMorphStereo | These describe or apply the recording space, not the music |
| Loading files | Audio.fromBuffer, Audio.fromMemory, Audio.fromMemoryWithBrowserFallback | Decoding plus method-style access to common functions |
New to audio terms such as BPM, STFT, or chroma? See the Glossary. For a cross-binding feature map, see Feature Map; for the mastering processor registry and the mixing scene format, see Mastering Processors and Mixing Scene JSON.
Installation
npm install @libraz/libsonareyarn add @libraz/libsonarepnpm add @libraz/libsonareImport
The package has five JavaScript entries. The main entry carries everything; the others are narrower bundles for specific realms. The raw WASM assets, the default HRTF set, the migration data and the JSON Schemas are separate subpath exports, listed in Installation.
| Entry | Import path | Contains | Use it when |
|---|---|---|---|
| Main | @libraz/libsonare | The full API: analysis, effects, mastering, mixing, projects, realtime engine | Almost always |
| Analysis | @libraz/libsonare/analysis | Analysis and features only: no mastering, mixing, realtime, or project APIs | You want the smallest download for analysis alone |
| Worklet | @libraz/libsonare/worklet | The AudioWorklet-side runtime, including SonareEngine, SonarePlaybackNode, SonareStreamAnalyzerNode and SONARE_METER_RING_PROTOCOL_VERSION | Code running inside an AudioWorkletGlobalScope |
| Worker | @libraz/libsonare/worker | The offline worker script behind OfflineWorkerClient | Running analysis off the main thread; see Workers |
| Vocal-edit worker | @libraz/libsonare/vocal-edit-worker | The worker script behind VocalEditWorkerClient | Vocal-edit drafts and render jobs off the main thread |
See Package Artifacts for the files each entry ships. The bundles target ECMAScript 2020.
import {
init,
Audio,
detectBpm,
detectKey,
detectBeats,
detectOnsets,
analyze,
version
} from '@libraz/libsonare';Initialization
init(options?)
Initializes the WASM module. Call it once, before any other function that needs the module.
async function init(options?: {
locateFile?: (path: string, prefix: string) => string;
wasmBinary?: ArrayBuffer | Uint8Array;
moduleFactory?: (options?: {
locateFile?: (path: string, prefix: string) => string;
wasmBinary?: ArrayBuffer | Uint8Array;
}) => Promise<SonareModule>;
}): Promise<void>Options apply on the first call only. Calling init() again with no options, or with the same options (functions compared by reference), resolves immediately. A second call whose options differ throws SonareError with InvalidState, naming the option. Every function that needs the module throws InvalidState when called before init() resolves.
init() also compares the loaded module's ABI version with the one the package was built against and throws AbiMismatch (code 10) when the .wasm and the JavaScript come from different builds, which a stale cache or a custom wasmBinary / locateFile can produce. The versions that were loaded are reported by abiVersion() and capabilities().abi.
Your first call
import { init, detectBpm } from '@libraz/libsonare';
await init(); // once, at app start
const bytes = await (await fetch('/song.mp3')).arrayBuffer();
const ctx = new AudioContext();
const decoded = await ctx.decodeAudioData(bytes);
const samples = decoded.getChannelData(0); // Float32Array, first channel
const bpm = detectBpm({ samples, sampleRate: decoded.sampleRate });
console.log(`${bpm.toFixed(1)} BPM`);Pass the sampleRate the samples were decoded at. To serve the .wasm from another path, pass locateFile:
await init({
locateFile: (path, prefix) => `/custom/wasm/path/${path}`
});Once that works, move to analyze, mastering, mixing, or streaming.
isInitialized()
Checks whether the module is initialized.
function isInitialized(): booleanversion()
Returns the library version.
function version(): string // e.g., "2.0.0"One-shot request objects
The top-level one-shot analysis, effects, mastering, metering, feature, mixer, and voice-changer APIs use a named request object as their canonical form. Every input is named, optional settings can grow without changing argument order, and TypeScript can guide you to the matching *Request type. Positional forms, (samples, sampleRate, options?), are compatibility overloads with identical defaults, validation, errors, results, and progress behavior. Every call scans its input for NaN and infinity and refuses it with a RangeError; there is no option to skip the scan.
// Preferred request-object form
const bpm = detectBpm({ samples, sampleRate });
const mastered = masterAudio({
samples,
sampleRate,
preset: 'pop',
overrides: { loudness: { targetLufs: -14 } },
onProgress: (progress, stage) => console.log(stage, progress),
});
// Positional form
const legacyBpm = detectBpm(samples, sampleRate);A request object refuses a key its entry point does not declare, naming the key and the keys it accepts: detectBpm({ samples, sampleRate, validate: false }) throws TypeError: detectBpm: unknown key validate (expected bpmMax, bpmMin, sampleRate, samples), and masterAudio({ samples, sampleRate, loudness: { targetLufs: -14 } }) throws TypeError: masterAudio: unknown key loudness (expected cancel, onProgress, overrides, preset, sampleRate, samples), since stage config belongs under overrides. Nested options objects and the options bag of a positional form refuse unknown options the same way.
The request fields use the same camelCase names on the Node and WASM packages. Python takes positional and keyword arguments (detect_bpm(samples, sample_rate)), rather than adopting a JavaScript-style options object.
Some result records, including EngineBounceResult, ProjectTempoCandidate, and VocalStateToken, have shallowly readonly properties. Copy a record with { ...result } before changing a top-level property; clone any nested array too if you intend to mutate its contents.
Canceling a long call
Requests that report progress also accept cancel, a predicate polled at the same native boundaries onProgress fires on. Return true and the call aborts.
import { ErrorCode, isSonareError, masterAudio } from '@libraz/libsonare';
let abandoned = false;
cancelButton.onclick = () => { abandoned = true; };
try {
const mastered = masterAudio({
samples,
sampleRate,
preset: 'pop',
onProgress: (progress, stage) => updateUi(progress, stage),
cancel: () => abandoned,
});
} catch (error) {
if (!(isSonareError(error) && error.code === ErrorCode.Cancelled)) throw error;
}A canceled call throws SonareError with code 8 (Cancelled) and leaves its outputs unallocated, so there is no partial result to inspect. Python takes the same predicate as cancel=.
Sample rates
sampleRate is required wherever samples are passed (detectBpm, stft, melSpectrogram, hpss, timeStretch, Audio.fromBuffer, StreamAnalyzer's StreamConfig.sampleRate, and the rest), and it is the rate of the buffer in your hand: no call assumes one. A call without it throws a TypeError (Audio.fromBuffer: sampleRate must be an integer), and a value that is not an integer in [8000, 384000] throws a RangeError.
Error Handling
Failures arrive as one of three classes, depending on who refused the input. The rule behind them is stated once on Error Contract; this section is its JavaScript view.
| Class | Raised by | Matched by isSonareError |
|---|---|---|
TypeError | A refused argument shape, whether the binding or the library refused it: a wrong type, a missing field, a key the call does not declare | No |
RangeError | A refused value: outside its domain, or an unknown id, name or parameter, whether the binding or the library refused it | No |
SonareError | A failure the arguments did not cause: the state of an object, the build, or the data | Yes |
SonareError is an Error subclass carrying a numeric code and its canonical codeName, mirroring the C ABI error enum. The same failure reports the same code on every binding (WASM, Node native, Python, C ABI), so branch on the code rather than the message. The package exports the ErrorCode enum, the SonareError class, and the isSonareError(value) type guard.
import { ErrorCode, isSonareError, Mixer } from '@libraz/libsonare';
try {
const mixer = Mixer.fromJson(sceneJson, { sampleRate: 48000 });
} catch (error) {
if (error instanceof TypeError || error instanceof RangeError) {
// An argument was refused; fix the call site.
console.error(`bad argument: ${error.message}`);
} else if (isSonareError(error) && error.code === ErrorCode.InvalidFormat) {
// e.g. 'Mixer.fromJson: strips[0].inserts[0].processor must name a known processor'
console.error(`scene rejected: ${error.message}`);
} else {
throw error;
}
}Which failure raises which error
| Failure | Raises |
|---|---|
Calling a function before init() resolves | SonareError InvalidState (7) |
A second init() with different options | SonareError InvalidState (7), naming the option |
.wasm and JavaScript from different builds | SonareError AbiMismatch (10) |
| Any method on a released or destroyed handle | SonareError InvalidState (7) |
A mixer scene that is not valid, or that names an unknown insert or a value its processor refuses (Mixer.fromJson); a project document that is not valid (Project.fromJson); a chain-config document with an unknown key (masteringChainConfigFromJson) | SonareError InvalidFormat (2) |
An unknown preset name (masterAudio({ preset: 'nope' }), mixingScenePreset) | RangeError |
An argument a Project, RealtimeEngine, Mixer setter or synth patch call refuses: an out-of-range value, an unknown or zero id, an unknown name or engineParams key, a malformed patch | RangeError (TypeError for a wrong type), never a SonareError |
| A refusal caused by earlier configuration: a full binding, strip or sidechain table, a master-strip setter before a master strip exists, a bounce whose derived length does not fit | SonareError InvalidState (7) |
An automation id for an unknown target or parameter (resolve*AutomationId), or a parameter that is not realtime-safe | RangeError; no call returns -1 |
A rejected STFT or stream configuration (nFft 0, a StreamConfig field out of domain) | RangeError |
| A canceled call | SonareError Cancelled (8) |
A null or wrongly typed argument, such as a samples that is not a Float32Array | TypeError |
Empty or non-finite audio; a sampleRate that is not an integer in [8000, 384000]; a fractional integer argument; two buffers whose lengths must match; a binding-resolved name that is unknown (such as a keyRoot) | RangeError |
A string with an embedded NUL passed to an entry point that checks for it (noteToHz, Project.fromJson, masteringPresetParams) | RangeError naming the field |
Mixer.fromJson reports InvalidFormat both for a document that is not valid JSON and for a field the mixer rejects; the message names the entry and the field path, Mixer.fromJson: strips[0].inserts[0].processor must name a known processor.
Every one-shot that takes samples and a sample rate checks them before the core is reached, so no raw embind BindingError reaches a caller. The facades reject non-finite numbers, invalid enum or index values, and oversized resources instead of clamping them; treat these as invalid input. Because a refused argument is a RangeError, a handler written only for isSonareError does not catch it: catch RangeError and TypeError for bad arguments, and branch on the code for the rest. The offline and vocal-edit worker clients and the AudioWorklet processors keep the class and any SonareError code of the failure across the thread boundary.
Error codes
ErrorCode | Value |
|---|---|
Ok | 0 |
FileNotFound | 1 |
InvalidFormat | 2 |
DecodeFailed | 3 |
InvalidParameter | 4 |
OutOfMemory | 5 |
NotSupported | 6 |
InvalidState | 7 |
Cancelled | 8 |
EncodeFailed | 9 |
AbiMismatch | 10 |
StaleResult | 11 |
Unknown | 99 |
AbiMismatch is made by the bindings, never by the core: it reports a native module whose ABI version differs from the one the package expects (WASM in init(), Node when the addon is required, Python on first library use); Installation lists the causes and fixes. The other codes match Python's SonareError.code and the C ABI SonareError enum, and the Python CLI maps them onto its exit codes. For the same failures on Node, Python, the C ABI, and the CLI, see the error contract.
Build and Environment
capabilities()
Describes the build that is actually loaded, the same report the CLIs print as doctor. Synchronous, and valid only after init().
function capabilities(): {
version: string;
abi: { project: number; engine: number };
platform: string;
features: {
mastering: boolean;
mixing: boolean;
mixingAssistant: boolean;
graph: boolean;
fx: boolean;
ffmpeg: boolean;
instrumentParamAutomation: boolean;
arrangement: boolean;
project: boolean;
acousticSim: boolean;
playback: boolean;
pitchEditor: boolean;
vocalEdit: boolean;
voiceChanger: boolean;
assist: boolean;
liveDevices: boolean;
};
decode: { builtin: string[]; ffmpeg: string[] };
simd: string;
hardwareConcurrency: number;
}Branch on features instead of guessing. decode.builtin lists the formats the module can open before you ask the browser to fall back, and simd reads "wasm-simd128" for the shipped build.
| Flag | Guards |
|---|---|
mastering | masterAudio, masterAudioStereo, StreamingMasteringChain, the named mastering processors |
mixing | Mixer, mixStereo, and the mixing scene functions |
mixingAssistant | mixingAssistantSuggest |
fx | The effects subsystem |
ffmpeg | FFmpeg decoding (false in the browser package) |
instrumentParamAutomation | Instrument-parameter automation targets |
arrangement | Project, clips, and the arrangement subsystem |
acousticSim | analyzeImpulseResponse, detectAcoustic, estimateRoom, synthesizeRir, roomMorph* |
pitchEditor | Note and pitch editing |
vocalEdit | Vocal-edit drafts and render jobs |
voiceChanger | RealtimeVoiceChanger, voiceChange* |
playback | PlaybackRenderer (upmix, binaural, speaker output) |
graph | The routing graph library |
project | Project documents: build, edit and render |
assist | The composition-assist injection seam (control and offline use only) |
mixingAssistant and instrumentParamAutomation are the two probes a host is most likely to need and least likely to reach for, because the entry points they guard stay registered whether or not the subsystem was built. mixingAssistantSuggest and the instrument-parameter automation targets exist as functions in every module and throw when the subsystem is absent, so typeof fn === 'function' is not a capability check. instrumentParamAutomation reports false in a build without the arrangement subsystem; mixingAssistant is compiled out of the analysis-only module, so that build reports false even though the symbol is there.
systemInfo()
Reports the host the module runs on: core counts, memory sizes and how the library parallelizes its work. Synchronous, and valid only after init().
function systemInfo(): {
cpu: { logicalCores?: number; physicalCores?: number };
memory: { totalGb?: number; availableGb?: number };
parallel: { enabled: boolean; workers: number; strategy: string };
}A fact the platform cannot report is absent from its object, never 0. parallel.workers is at least 1.
capabilityCatalog()
Returns a machine-readable catalog of every processor, its parameter descriptors, and the built-in preset lists. It is the same canonical JSON the C ABI publishes and Python exposes as capability_catalog, validated against schemas/capability-catalog.schema.json.
function capabilityCatalog(): {
version: string;
abi: { project: number; engine: number };
processors: MasteringProcessorCatalogEntry[]; // one entry per processor; fields are on the Capability Catalog page
chain: CapabilityCatalogChain; // how every flat mastering chain key is described
presets: {
mastering: string[];
synth: string[];
mixingScene: string[];
voiceChanger: string[];
playbackRoom: string[]; // always present; empty when playback is compiled out
};
masteringPresets: Array<{
name: string;
kind: 'mastering' | 'restoration';
targetLufs?: number; // absent for a restoration preset
truePeakCeilingDbtp?: number;
maxLimiterGainReductionDb?: number;
}>;
}This is what you build a generic parameter UI from: every slider's range, default, unit, and axis (uiMin / uiMax, scale) comes from the catalog instead of a table you maintain by hand. The processor entry and parameter descriptor fields are listed on Capability Catalog. A bound that is absent (undefined) means the core knows of no limit on that side; treat it as "unbounded or unknown", not as zero.
A published bound is a hard constraint, not a recommended UI range
Bounds are measured with every other parameter of the processor at its default, so two parameters that constrain each other each report the other's default; a sample-rate-derived bound such as an EQ band*.frequencyHz ceiling reads as the un-prepared 24000; and an exclusive bound is reported as the limit it excludes. Reading a catalog bound explains each case.
abiVersion()
Returns the aggregate native ABI version across the C POD surfaces (the packed value the loader checks at init()). Persist or compare it when loading a prebuilt binary so an incompatible JS/native artifact pair fails early.
function abiVersion(): numberprojectAbiVersion()
ABI version of the project/editing POD API used by Project serialization, bounce, and realtime-engine clip exchange.
function projectAbiVersion(): number | undefined // undefined when the project feature is compiled outvoiceChangerAbiVersion()
ABI version of the realtime voice-changer POD config used by native and FFI APIs. This is separate from preset JSON schemaVersion, currently 4. Check user-authored presets with realtimeVoiceChangerValidatePresetJson(...) before accepting them.
function voiceChangerAbiVersion(): numberVoice Preset Accessors
Use these when you need the canonical voice-character preset ID or the resolved flat POD config without parsing preset JSON.
function voiceCharacterPresetId(ordinal: number): VoicePresetId
function realtimeVoiceChangerPresetConfig(preset: VoicePresetId): RealtimeVoiceChangerConfigvoiceCharacterPresetId(...) takes an ordinal in [0, 11] (voiceCharacterPresetId(0) is 'neutralMonitor'); a non-integer or unknown ordinal throws a RangeError, a non-number a TypeError. realtimeVoiceChangerPresetConfig(...) takes the preset id only, since an ordinal is a TypeError, and an unknown id is a RangeError listing the valid ids.
The resolved RealtimeVoiceChangerConfig uses camelCase keys on both JavaScript surfaces (inputGainDb, wetMix, formantFactor, formantMode, limiterIspCeilingDbtp, and so on). The equivalent C and Python POD fields remain snake_case.
Realtime environment helpers
These describe the runtime capabilities used by RealtimeEngine. Check them before wiring AudioWorklet/SharedArrayBuffer paths, especially when the page may run under different browser isolation policies.
function engineAbiVersion(): number
const engineAbi = capabilities().abi.engine; // the engine ABI version that was loaded
const hasSab = typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined';
const hasWorklet = typeof AudioWorkletNode !== 'undefined';Whether SharedArrayBuffer, Atomics and AudioWorkletNode exist is a property of the page, so test them yourself. capabilities().features.ffmpeg reports whether the loaded build can decode through FFmpeg. The browser/WASM npm package works on decoded PCM and normally reports false; Python/native builds are the intended place to decode files directly.
Browser support and bundle size
Browser Compatibility has the supported browser and Node.js versions, and Bundle Size has the file sizes.
Releasing Native Handles
Every class that owns a native handle (Mixer, StreamAnalyzer, Project, ProjectTimeline, RealtimeEngine, ClipPageProvider, ClipPageStreamer, StreamingEqualizer, StreamingMasteringChain, StreamingRetune, RealtimeVoiceChanger, PlaybackRenderer, and the others) has an idempotent destroy() and implements [Symbol.dispose](), so the using declaration releases it when the scope ends, even on an exception. Project and VocalEditSession release the same way. The clients that wait on a worker (OfflineWorkerClient, VocalEditWorkerClient) return a Promise from destroy() and implement [Symbol.asyncDispose](), for await using. Audio is released the same way: destroy() and [Symbol.dispose]() drop its samples, and a later read of audio.data or call of an instance method throws SonareError InvalidState (code 7).
import { init, Mixer, mixingScenePreset } from '@libraz/libsonare';
await init();
{
using mixer = Mixer.fromJson(JSON.stringify(mixingScenePreset('vocalReverbSend')), { sampleRate: 48000 });
// ... process blocks; the mixer is released at the closing brace.
}The package installs Symbol.dispose when the host lacks it, so the methods exist everywhere. The using syntax itself needs TypeScript 5.2 or later (with esnext.disposable in lib), a bundler that lowers it, or a runtime with native support; otherwise call destroy() in a finally block. A method called on a released handle throws SonareError with InvalidState.
Audio, project and live-device examples
Phase, tags and stereo analysis
Capture phase with stft to reconstruct the original sample length with istft. Pass one equally sized sample array per channel to the encoder. The tag reader takes the encoded bytes. Stereo pair analysis takes a left and a right plane for both inputs.
import { init, encodeAudio, istft, masteringAnalyzePair, readAudioTags, stft }
from '@libraz/libsonare';
await init();
const sampleRate = 16000;
const mono = Float32Array.from(
{ length: sampleRate }, (_, i) => 0.2 * Math.sin(2 * Math.PI * 440 * i / sampleRate),
);
const stereo = [mono, mono];
const { magnitude, phase } = stft({ samples: mono, sampleRate, nFft: 256, hopLength: 64, phase: true });
if (!phase) throw new Error('STFT phase is unavailable');
const reconstructed = istft({ magnitude, phase, nFft: 256, hopLength: 64, lengthSamples: mono.length });
const wav = encodeAudio({ channels: stereo, sampleRate, format: 'wav', tags: { title: '440 Hz' } });
console.log(readAudioTags({ data: wav }).title);
const quieter = mono.map(sample => sample * 0.5);
console.log(masteringAnalyzePair({
analysis: 'match.referenceLoudness', source: stereo, reference: [quieter, quieter], sampleRate,
}));Project readers
Tempo and time-signature readers return stored segments. The position reader reports the effective tempo, bar and beat at a PPQ position. Annotation readers preserve the stored order, including overlapping sections. Each automation lane has a project-assigned ID.
import { init, Project } from '@libraz/libsonare';
await init();
const project = new Project();
try {
project.setTempoSegments([{ startPpq: 0, bpm: 120 }]);
project.setTimeSignatures([{ startPpq: 0, numerator: 3, denominator: 4 }]);
console.log(project.tempoSegments(), project.timeSignatures());
const ppq = project.barStartPpq(1);
console.log(project.positionAtPpq(ppq), project.secToPpq(project.ppqToSec(ppq)));
project.annotateKeys([{ startPpq: 0, endPpq: 6, tonicPc: 0, mode: 'major' }]);
project.annotateChords([{ startPpq: 0, endPpq: 3, rootPc: 0, quality: 'major' }]);
project.annotateSections([
{ startPpq: 0, endPpq: 4, label: 'Verse' },
{ startPpq: 3, endPpq: 6, label: 'Chorus' },
]);
console.log(project.keyAnnotations(), project.chordAnnotations(), project.sectionAnnotations());
console.log(project.mixerScene(), project.unresolvedSoundFontUris());
const trackId = project.addTrack({ kind: 'audio', name: 'Voice' });
const laneId = project.addAutomationLane(trackId, {
targetKind: 'trackFaderDb',
points: [{ ppq: 0, value: -3 }],
});
console.log(laneId, project.automationLanes());
} finally {
project.destroy();
}MIDI CC bindings
Set consume to route matching controller messages to the parameter and suppress their delivery to the instrument. It defaults to false. The reader returns a snapshot whose order is unspecified.
import { init, RealtimeEngine } from '@libraz/libsonare';
await init();
const engine = new RealtimeEngine({ sampleRate: 48000 });
try {
engine.bindMidiCc({ ccNumber: 1, paramId: 42, consume: true });
console.log(engine.midiCcBindings());
} finally {
engine.destroy();
}Live devices
This package reports features.liveDevices as false. LiveSession and its enumeration methods throw a coded NotSupported error with reason notCompiledIn.
import { capabilities, init, isSonareError, LiveSession } from '@libraz/libsonare';
await init();
console.log(capabilities().features.liveDevices); // false
try {
LiveSession.audioDevices();
} catch (error) {
if (!isSonareError(error)) throw error;
console.log(error.codeName, error.reason); // NotSupported, notCompiledIn
}Reference Pages
The reference is split by subject. Every page below assumes the installation, import, and initialization steps above.
- Analysis: song-level analysis, feature extraction, and Roman-numeral chord analysis.
- Helpers and Conversions: librosa-compatible helpers, scale quantization, unit conversion, resampling, and chord functions.
- Feature Extraction: STFT, mel, MFCC, chroma, spectral features, waveform peaks, and the CQT/VQT family.
- Pitch and Notes: pitch tracking, polyphonic note analysis, note-pitch decomposition, and percussive events.
- Stems and Remix: component and stem decomposition and aligned-interval remixing.
- Effects: audio effects and editing DSP.
- Room Acoustics: impulse-response analysis, room estimation, and room-impulse-response synthesis.
- Mastering: the mastering chain, named processors, presets, and the one-shot dynamics and repair processors.
- Streaming and Realtime: block-by-block processors, the streaming mastering chain, and the incremental
StreamAnalyzer. - Audio, Metering and Mixing: the
Audioclass, metering, take alignment, mixer strips, and the mixing API. - Projects:
Project,ProjectTimelineand the vocal-edit sessions, with their lifecycle. - Realtime Engine: the
RealtimeEngineclass, its lifecycle, and the lane limit. - SonareEngine: the AudioWorklet facade of the realtime engine.
- Instruments and Live MIDI: the synth catalog,
SampleBank, SoundFont loading, Web MIDI and microphone input. - Types and Enumerations: type definitions, enumerations, and the type export index.
- Workers:
OfflineWorkerClientandVocalEditWorkerClientfor running offline work off the main thread.
Performance Summary
| API | Load | Notes |
|---|---|---|
StreamAnalyzer | Real-time | Per-chunk processing, ~2ms/frame, updating BPM/key/chord estimation |
Mixer | Real-time | Scene-based block processing with automation and meters |
analyze | Heavy | All-in-one analysis pipeline |
hpss / harmonic / percussive | Heavy | STFT + median filtering |
timeStretch | Heavy | Phase vocoder |
pitchShift | Heavy | Time stretch + resample |
stft | Medium | Multiple FFT operations |
melSpectrogram / mfcc | Medium | STFT + filterbank |
chroma | Medium | STFT + chroma filterbank |
pitchYin / pitchPyin | Medium | Per-frame pitch detection |
resample | Medium | High-quality resampling |
detectBpm / detectKey | Light | Single result |
detectBeats / detectOnsets | Light | Frame-based detection |
| Unit conversion functions | Light | Pure computation |
normalize / trim | Light | Simple processing |