JavaScript/TypeScript Instruments and MIDI API
The built-in synthesizer catalog, the host-supplied SampleBank, SoundFont playback and the browser helpers that feed live MIDI and microphone audio into an engine. The classes that host them are on Projects and Realtime Engine.
Where each task lives
| Goal | Use | Guide |
|---|---|---|
| Pick a built-in synth voice | synthPresetNames(), synthPresetPatch(name), engine.setSynthInstrument(...) | Native Synth |
| Play through a SoundFont | project.loadSoundFont(bytes, { uri }) / engine.loadSoundFont(bytes) | SoundFont Player |
| Drive the engine from a hardware/Web MIDI device | bindWebMidi(engine, ...) Browser only | MIDI Input |
| Feed a live microphone into the engine | bindMicrophoneInput(context, engine, ...) Browser only | Recording and Takes |
bindWebMidi(...) and bindMicrophoneInput(...) are browser-only helpers that wire Web MIDI / a MediaStream into a live RealtimeEngine.
Lifecycle
Project can hold a default SoundFont and multiple named SoundFonts. loadSoundFont, clearSoundFont, soundFontPresetCount, and soundFontManifest take optional { uri } options; omit uri to select the default. An SF2 bounce binding's soundFontUri selects a named font for that render, and omitting it selects the default. RealtimeEngine.loadSoundFont(bytes) uses the engine's separate single SoundFont slot. A malformed project load throws and keeps the previous font in the selected slot. SampleBank is a WASM heap object: build it on the control thread, add every sample and zone before the bounce that binds it starts, and destroy() it (idempotent, using works) once every bounce that names it has finished. The helpers bindWebMidi and bindMicrophoneInput return a binding whose destroy() disconnects it; using works there too. Nothing here is realtime-safe except the engine's own MIDI input queue, which takes events at an offset into the next processed block. An unknown preset name or malformed patch is a RangeError. See Error Contract.
Built-in synth catalog
function synthPresetNames(): string[]
function synthPresetPatch(name: string): SynthPatch
function synthEngineParamInfo(engineMode: SynthEngineMode): SynthParamInfo[]
function synthPatchParamInfo(): SynthPatchParamInfo[]
function synthEnumTables(): SynthEnumTables
function synthGsDrumKitName(program: number): string | null
function synthGsDrumKitIsVoicedApart(program: number): boolean | null
function synthGsVariationIsVoicedApart(bank: number, program: number): boolean | nullSampleBank
class SampleBank {
readonly nativeId: number; // Identity a binding names this bank by, so no raw pointer crosses into JS. Hosts pass the `SampleBank` itself as `sampleBank`.
constructor(); // Create an empty bank.
// Copy mono float frames into the bank and return the new sample's index, which SampleZoneDesc.sampleIndex names. The frames are copied, so the array may be reused afterwards.
//
// Loop points are clamped inside the sample and a loop mode whose loop survives the clamp empty is dropped, so a malformed loop plays as an unlooped sample rather than as a wrap over nothing. An empty array, and a bank that would exceed 67,108,864 sample points, throw.
//
// A NaN or Inf frame, `fineTuneCents` or `sourceRate` throws too, and the bank is left unchanged. Such a value is unattributable once stored: the reader's interpolation spreads one bad frame across the whole sustain, and a bad tuning offset renders the voice silent with no error raised.
addSample(data: Float32Array, desc?: SampleDesc): number;
// Append a key/velocity rectangle to a keymap set, creating any sets below it. A patch names a set; the first zone in it covering a note is the one that sounds.
//
// Every bound defaults on its own (see SampleZoneDesc), so an empty rectangle is the whole keyboard at every velocity and narrowing one axis leaves the other whole. A `sampleIndex` the bank does not have, an inverted key or velocity range, and a `setIndex` at or above 4096 all throw.
addZone(zone?: SampleZoneDesc): void;
get sampleCount(): number; // Samples added so far.
get setCount(): number; // Keymap sets the bank has (one past the highest index used).
destroy(): void; // Release the underlying WASM object. Idempotent, as the Node facade is.
[Symbol.dispose](): void; // Releases the handle through destroy, so the instance works with `using`.
}Live MIDI and microphone input
function bindWebMidi(engine: WebMidiEngine, options?: BindWebMidiOptions): Promise<WebMidiBinding>
function isWebMidiAvailable(): boolean
interface BindWebMidiOptions {
destinationId?: number; // Realtime-engine MIDI destination receiving the live input source. Default `0`.
group?: number; // UMP group used for MIDI 1.0 channel voice events. Default `0`.
inputIds?: readonly string[]; // Restrict binding to specific Web MIDI input ids. Omit or empty = all connected inputs.
sysex?: boolean; // Request SysEx-capable access from the browser. Default `false`.
software?: boolean; // Request software ports from the browser where supported. Default `true`.
ccBindings?: readonly ProjectMidiCcBinding[]; // Bind CC-to-parameter mappings before ports are connected.
timestampToOffsetInBlockSamples?: (eventTimeMs: number) => number; // Convert a Web MIDI event timestamp to an offset in samples into the next block drained (clamped to its last frame, negative reads as 0). Return a block-relative offset, not the timestamp scaled to samples: an absolute value lands every event on one frame. Omit for offset 0. Exclusive with context.
context?: WebMidiAudioContext; // The AudioContext the engine renders in. Each event's timestamp is placed on its clock by webMidiEventContextTime, delayed by scheduleAheadSec, and pushed with `contextTimeSec`, so events keep their spacing to the sample instead of bunching at block heads. Requires an engine whose pushes take `contextTimeSec` (the AudioWorklet `SonareEngine`). Exclusive with timestampToOffsetInBlockSamples.
scheduleAheadSec?: number; // Seconds each event is delayed on the context clock in context mode. Default: the context's `baseLatency + outputLatency` (a missing or non-finite value reads as 0) plus two render quanta, read per event. A smaller value answers sooner and plays more events late, at the next block's start; a larger one keeps every event on its sample at the cost of that delay. `0` is allowed.
onInputsChanged?: (inputs: WebMidiInputInfo[]) => void; // Observe hot-plug updates after the helper rebinds matching inputs.
filter?: (message: WebMidiMessage) => boolean; // Called with each message the binding is about to push, before it reaches the engine; returning a falsy value drops that message (a MIDI-learn mode, for instance). System messages the binding never pushes are not offered.
}
interface WebMidiBinding {
access: MidiAccessLike; // The browser's MIDIAccess object.
inputs(): WebMidiInputInfo[]; // Current snapshot of every input port, bound or not.
destroy(): void; // Stops listening on every bound input and for hot-plug changes, releases what each input still held, and clears the engine's MIDI input source; both last steps are skipped when a newer binding has replaced the source. Safe to call more than once.
[Symbol.dispose](): void; // Same as destroy, so the binding works with `using`.
}
function bindMicrophoneInput(
context: AudioContext,
engine: SonareRealtimeEngineNode | AudioWorkletNode,
options?: BindMicrophoneInputOptions,
): Promise<MicrophoneInputBinding>