Skip to content

Play a Synth from a USB Keyboard with Web MIDI ​

Live MIDI input turns the realtime engine into an instrument you can play. A note pressed on a USB keyboard becomes a note-on event, the engine routes it to a bound synthesizer, and you hear it on the next audio block — no file, no offline render.

libsonare's RealtimeEngine accepts live MIDI through the same realtime-safe entry points that drive transport, clips, and automation. In the browser, a small Web MIDI bridge (bindWebMidi) wires the platform's MIDI ports straight into that engine for you.

There are two common starting points:

If you haveStart with
An on-screen keyboard or sequencer step written in your appimmediate pushMidiNoteOn / pushMidiNoteOff calls
A USB keyboard or external controllerbindWebMidi, which uses the live input-source calls for you

MIDI destination

A MIDI destination is not a speaker output. It is an internal instrument slot. MIDI events go to a destination id such as 0; the instrument bound to that id decides what sound is produced.

Where this sits

This page is about playing the engine from a controller. To bind the instruments those notes reach, see Native Synth (patch-driven synthesizer) and SoundFont Player (GS/GM .sf2 playback). To record what you play into a timeline, see Recording and Takes. Microphone audio input is a separate path — see the note at the end. New to MIDI? Start with MIDI Basics.

The live MIDI path ​

The browser receives MIDI bytes, bindWebMidi converts them into engine events, and the destination's instrument produces audio during process(...). Each arrow below is one hop on that path — from raw key press to sample data — and the loop label marks the parts that repeat on every note.

USB keyboard to audio output
LOOP · PER MIDI MESSAGEnote-on /note-off / CCpushMidiInput*(sampletimestamp)route bydestination idrender in process()USB keyboardbindWebMidiRealtimeEngineInstrument (dest. 0)Audio output block
Everything left of the engine happens once per event; everything right of it happens once per audio block.

If you hear silence, check the path in this order: browser permission, bindWebMidi input list, destination id, bound instrument, then the AudioWorklet/output wiring.

The MIDI destination model ​

The engine does not play notes directly — it routes them to MIDI destinations, and each destination has an instrument bound to it. A destination is identified by a small integer id (default 0). You bind an instrument once, then every live event or scheduled clip aimed at that id renders through it.

Three instrument kinds can sit on a destination:

Bind withInstrumentSee
setBuiltinInstrument(destinationId, config)The built-in waveform synth (the data-free floor)—
setSynthInstrument(destinationId, patch)The patch-driven NativeSynthNative Synth
setSf2Instrument(destinationId, config)A GS-compatible SoundFont playerSoundFont Player

MIDI 2.0 and MPE expression

MPE gives each sounding note its own channel inside a zone, so bend and pressure can shape one note of a chord; MIDI Basics explains zones, manager and member channels, and UMP groups.

The built-in waveform synth (setBuiltinInstrument), NativeSynth (setSynthInstrument), and SoundFont player (setSf2Instrument) receive MIDI 2.0 channel-voice UMPs at full value width. Note velocity, controllers, pressure, and pitch bend retain the precision supplied by the MIDI 2.0 message.

The built-in synth and NativeSynth apply channel pressure, polyphonic key pressure, and per-note pitch bend. The SoundFont player applies full-width note velocity, channel pressure, pitch bend, and MIDI 2.0 per-note pitch, but intentionally ignores polyphonic key pressure. MPE-style member channels can therefore carry channel expression to each player, while poly-pressure expression is unavailable on SoundFont.

A zone-wide command sent on an MPE manager channel, such as CC64 sustain, reaches every member channel of the zone on the built-in synth.

NativeSynth and the SoundFont player use RPN 0 for bend range, and the built-in synth handles its MPE zone configuration. Generic high-resolution RPN/NRPN and 14-bit CC parameter mappings live one level up, in the engine's bindMidiCc(...) layer described below. See Native Synth for NativeSynth's bend and expression details.

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

await init();

const engine = new RealtimeEngine({ sampleRate: 48000, maxBlockSize: 128 });

// Destination 0 → a NativeSynth preset (see synthPresetNames()).
engine.setSynthInstrument(0, { preset: 'sawLead' });

// You can run several destinations at once, each with its own instrument.
engine.setSf2Instrument(1, { gain: 1 });

Use clearMidiInstrument(destinationId) to unbind one, and the midiInstrumentCount property to see how many are live. Multiple destinations let one engine host a layered rig: a lead synth on 0, drums on 1, and so on.

Rebinding a destination while the transport rolls fades the outgoing instrument over 10 ms and starts the new one from its default channel state. Resend any program or bank with pushMidiProgram after the change; see Realtime Engine.

Queueing live events ​

Live events are queued, not played synchronously. Each call hands the engine a sample position at which the event should fire; the next process(...) block consumes everything due in that block. That is what makes timing tight: the event lands at an exact frame, not "whenever the message arrived".

There are two queueing paths, and you should pick one per destination. Rule of thumb: use the immediate commands when your own code generates the events (a sequencer step, an on-screen keyboard); use the input source when events arrive from outside with their own timestamps (a hardware keyboard via bindWebMidi), because that lane carries the per-port timestamp the Web MIDI bridge needs.

CallTargetsTiming argumentNotes
pushMidiNoteOn / pushMidiNoteOff / pushMidiCcOne destinationrenderFrame?Omit it to fire as soon as possible
pushMidiProgramOne destinationrenderFrame?One MIDI 2.0 Program Change; see below
pushMidiSysexOne destinationrenderFrame?Complete frame, 0xF0 to 0xF7, 1..512 bytes
pushMidiUmpOne destinationrenderFrame?1 to 4 words; MT 0x4 keeps full width, MT 0x3 / 0x5 are rejected
pushMidiPanicEvery destinationrenderFrame?Releases every sounding note
pushMidiInput* (NoteOn, NoteOff, Cc, PitchBend, ChannelPressure, PolyPressure, Program, Ump)The input sourceoffsetInBlockSamplesNeeds setMidiInputSource(destinationId); the lane the Web MIDI bridge feeds
  • Immediate engine commands — pushMidiNoteOn / pushMidiNoteOff / pushMidiCc each take a destinationId and an optional renderFrame; omit it to fire as soon as possible. pushMidiPanic(renderFrame?) takes only the optional renderFrame and releases every sounding note on all destinations at once.
  • Refusals — every live push refuses a value outside its MIDI range with an error naming the argument and the range, such as channel must be an integer in [0, 15] or bend14 must be an integer in [0, 16383], on destination pushes and input-source pushes alike: RangeError from the package classes on Node and WASM (the raw embind engine refuses with a CppException), SonareValueError in Python, InvalidParameter in C, each prefixed with the calling function's name. A negative renderFrame is refused the same way; "not given" is absence, never -1.
  • The engine-owned live input source — setMidiInputSource(destinationId) opens a dedicated input lane, then pushMidiInputNoteOn / pushMidiInputNoteOff / pushMidiInputCc send events with a offsetInBlockSamples timestamp. pushMidiInputPitchBend, pushMidiInputChannelPressure, pushMidiInputPolyPressure, pushMidiInputProgram, and pushMidiInputUmp add the expression, program-change and raw-packet paths. Pushing while the input source is disabled fails with InvalidState, and a full input queue with OutOfMemory; a WASM build without the input source throws NotSupported.
  • Live SysEx — pushMidiSysex(destinationId, data, renderFrame?) queues a full SysEx (System Exclusive, a free-form manufacturer-specific message) frame to a destination; data is the complete message including the leading 0xF0 and trailing 0xF7 (1..512 bytes), and renderFrame follows the same omit-for-immediate convention as the other pushMidi* calls. Its primary use is delivering a GS/GM reset or a GS insertion-effect (EFX) selection to a live SF2-bound destination without stopping playback — see SoundFont Player for what that SysEx selects.
  • Raw UMP messages — pushMidiUmp(destinationId, words, renderFrame?) accepts an array or Uint32Array of 1–4 32-bit words, most significant first. The length must match the message type in the first word. MIDI 2.0 channel-voice messages (MT 0x4) keep their full value width; SysEx7/data messages (MT 0x3/0x5) are rejected, so use pushMidiSysex for those. The SonareEngine worklet facade accepts the same complete packet through pushMidiUmp(trackId, words, renderFrame?) (a legacy one-word number is also accepted), and its pushMidiInputUmp(words, offsetInBlockSamples = 0) covers the engine-owned input source.

Every binding exposes the same SysEx call; only the naming convention changes. data is the complete frame (leading 0xF0, trailing 0xF7, 1..512 bytes) and the last argument is the same optional render frame as the other pushMidi* calls (omitted, or None in Python, for immediate). Only the C ABI spells "immediate" as -1.

The destination instrument prepares a live SysEx payload on the control thread before it is queued. If preparation is refused, the call reports a refused argument (RangeError; InvalidParameter in C); retrying the same payload cannot fix that refusal. setMidiClips prepares every scheduled SysEx before publishing a replacement, so one refusal leaves the previously accepted schedule in place. Rebinding a destination also stages preparation for scheduled and already queued SysEx; a refusal (InvalidState) leaves the previous instrument binding and pending operations unchanged. A later prepare() rechecks scheduled payloads; if the bound instrument refuses one, the schedule is cleared and InvalidState is reported.

typescript
engine.pushMidiSysex(/* destinationId */ 0, gsResetOrEfxBytes);
typescript
// Same surface as the browser; data is a Buffer or Uint8Array.
engine.pushMidiSysex(0, gsResetOrEfxBytes);
python
# data is bytes / bytearray / memoryview; render_frame=None (the default) is immediate.
engine.push_midi_sysex(0, gs_reset_or_efx_bytes)
c
/* size must be 1..512; the C ABI keeps render_frame -1 = immediate. */
sonare_engine_push_midi_sysex(engine, /* destination_id */ 0,
                              data, size, /* render_frame */ -1);
typescript
// Immediate path: fire a note at the start of the next block.
engine.pushMidiNoteOn(/* destinationId */ 0, /* group */ 0, /* channel */ 0, /* note */ 60, /* velocity */ 100);
engine.pushMidiCc(0, 0, 0, /* controller */ 1, /* value */ 64);
engine.pushMidiNoteOff(0, 0, 0, 60, 0);

// Scheduled: the same call with a block-relative render frame.
engine.pushMidiNoteOn(0, 0, 0, 64, 100, /* renderFrame */ 64);

// Input-source path (what bindWebMidi uses under the hood):
engine.setMidiInputSource(0);
engine.pushMidiInputNoteOn(/* group */ 0, /* channel */ 0, 60, 100, /* offsetInBlockSamples */ 0);
engine.pushMidiInputCc(0, 0, 1, 64, 0);
engine.pushMidiInputNoteOff(0, 0, 60, 0, 0);
// engine.midiInputPendingCount  -> events waiting for the next process() block

group and channel are MIDI nibbles (0..15); note, velocity, controller, and value are 7-bit (0..127). A note-on with velocity 0 is treated as a note-off, exactly as the MIDI spec requires.

Program change and the receivers that follow it ​

pushMidiProgram(destinationId, group, channel, program, bank?, renderFrame?) and pushMidiInputProgram(group, channel, program, bank?, offsetInBlockSamples?) (C sonare_engine_push_midi_program, sonare_engine_push_midi_input_program) queue one MIDI 2.0 Program Change, timed like a note or CC. The bank is optional: pass { msb, lsb } (each 0 to 127) to select one, and omit it for none. Python spells them push_midi_program and push_midi_input_program with bank_valid, bank_msb and bank_lsb; there a non-zero bank_msb / bank_lsb with bank_valid false is refused. The SonareEngine worklet facade takes pushMidiProgram(trackId, group, channel, program, bank?, renderFrame?).

The message goes through the receiver's own program gates, so only some receivers act on it:

ReceiverFollows a program change?
SoundFont playerYes, unless the part's GS receive switches for program change or bank select are off
NativeSynth bound with useGmPrograms: true (Python use_gm_programs)Yes; each channel's voice is resolved from the bank and program
NativeSynth playing the GM kit (the drumKit preset, or a percussion patch with gmKit on)Yes; the program picks the GS drum set on every channel
Built-in synth, any other NativeSynth patch, a part whose GS program-change receive switch is off, an MPE member channelAccepted and ignored

Binding MIDI CCs to engine parameters ​

A CC can do double duty: reach the instrument and drive an engine automation parameter. bindMidiCc({ ccNumber, channel?, paramId, minValue?, maxValue? }) maps a controller's 7-bit value into [minValue, maxValue] for a registered parameter, while the CC still flows to the destination instrument.

typescript
// Register the parameter the engine should drive, then map mod wheel (CC1) to it.
engine.addParameter({ id: 42, name: 'cutoff', minValue: 0, maxValue: 1, defaultValue: 0.5 });
engine.bindMidiCc({ ccNumber: 1, channel: 0, paramId: 42, minValue: 0, maxValue: 1 });

// engine.midiCcBindings().length  -> 1
// engine.clearMidiCcBindings() -> remove all mappings

For high-resolution controllers, give the same descriptor a kind, which selects the controller format and which fields it reads:

kindFormatFields used
'controlChange7' (default)7-bit CCccNumber
'controlChange14'Paired 14-bit CCccNumber, ccLsbNumber
'rpn'RPNselectorMsb, selectorLsb
'nrpn'NRPNselectorMsb, selectorLsb

Omit channel to match every MIDI channel (255 is refused).

typescript
engine.bindMidiCc({
  kind: 'nrpn',
  channel: 0,
  ccNumber: 99,
  selectorMsb: 1,
  selectorLsb: 2,
  paramId: 42,
  minValue: 0,
  maxValue: 1,
});

addParameter also accepts unit (a display string), rtSafe, and defaultCurve ('linear', 'exponential', 'hold' or 'sCurve'). The one that matters here is rtSafe (default true): it declares whether the audio thread may change the parameter mid-playback. Keep it true for anything you intend to CC-bind and move while notes sound. Register it with rtSafe: false and the engine rejects every live write to it outright — from automation and from a bound CC, and from a direct setParameter(...) call — regardless of whether the transport is playing or stopped.

CC "learn" workflows

For an offline "wiggle a knob, capture which CC moved" flow, midiCcLearn (Python midi_cc_learn) works on captured ProjectMidiEvent data rather than the live engine. See Learn a CC and turn it into automation.

Mapping a device gesture to an expression axis ​

A controller profile says what a gesture means to the instrument on a destination: CC2 as breath force, channel pressure as loudness, a pitch bend as a pitch offset in cents. This is separate from bindMidiCc, which drives an engine parameter; a profile drives the instrument's own expression axes.

  • controllerProfileNames() lists the presets: 'gm', 'breath', 'breathAftertouch', 'mpe'.
  • engine.setControllerProfile(destinationId, name) replaces the destination's profile with a preset and clears every channel's accumulated axis values. An unknown name, a destination with no instrument, or an instrument with no profile throws.
  • engine.bindController(destinationId, binding) adds one ControllerBinding on top: input ('controlChange', 'channelPressure', 'polyPressure', 'pitchBend', 'velocity'), index (the CC number, used only by 'controlChange'), axis ('excitation', 'position', 'brightness', 'morph', 'loudness', 'pitchCents', 'vibratoDepth'; 'none' is refused), and optional lo, hi and curve. lo > hi inverts the gesture, and curve defaults to a linear 1.
  • clearControllerBindings(destinationId), controllerBindingCount(destinationId) and setControllerVelocityMeaningful(destinationId, meaningful) complete the set. Set the last to false when the device sends a constant velocity, so the bound axes carry the dynamics alone.
  • setControllerNoteTracking(destinationId, dimension, tracking) chooses which note a value addressed to a whole channel reaches when several sound on it: dimension is one of MPE_DIMENSIONS ('bend', 'pressure', 'timbre') and tracking one of NOTE_TRACKINGS ('last', 'lowest', 'highest', 'all'). It matters only inside an MPE zone while a channel holds more than one note.
typescript
import { controllerProfileNames } from '@libraz/libsonare';

controllerProfileNames();                         // ['gm', 'breath', 'breathAftertouch', 'mpe']
engine.setControllerProfile(0, 'breath');         // breath CC drives the excitation force
engine.bindController(0, { input: 'channelPressure', axis: 'loudness', lo: 0.2, hi: 1 });
engine.controllerBindingCount(0);                 // 5

Python uses bind_controller(destination_id, input=..., index=0, axis=..., lo=0.0, hi=1.0, curve=1.0) with keyword-only arguments, set_controller_profile, clear_controller_bindings, controller_binding_count, set_controller_velocity_meaningful, set_controller_note_tracking, and the module-level controller_profile_names(). Which axes each instrument voice reads is listed in Physical Models.

Swapping MIDI FX without hanging notes ​

Each destination can carry one MIDI-FX insert — a non-destructive transform on the event stream (transpose, channel filter, velocity curve, …) configured with a MidiFxConfig object.

typescript
// Transpose every incoming note up an octave.
engine.setMidiFx(/* destinationId */ 0, { transposeSemitones: 12 });
engine.clearMidiFx(0);   // clears this destination only (the id defaults to 0 if omitted)
typescript
engine.setMidiFx(0, { transposeSemitones: 12 });
engine.clearMidiFx(0);   // destinationId defaults to 0
python
engine.set_midi_fx(0, {"transposeSemitones": 12})
engine.clear_midi_fx(0)   # destination_id defaults to 0
c
sonare_engine_set_midi_fx(engine, /* destination_id */ 0,
                          "{\"transposeSemitones\": 12}");
sonare_engine_clear_midi_fx(engine, /* destination_id */ 0);

The config is the one bakeMidiFx accepts (the C ABI takes it as JSON text with the same keys): stages are keyed by their parameters, so include a stage's keys to enable it and omit them to skip it. An unknown key is refused with a SonareError naming it. Valid keys include transposeSemitones, velocityScale / velocityOffset / velocityGamma, quantizePpq / quantizeStrength, chordIntervals, and arpeggiatorIntervals / arpeggiatorStepPpq / arpeggiatorGatePpq. See Bake a MIDI-FX chain for the full key table.

setMidiFx replaces the insert in place without resetting the instrument's voices, but swapping onto a destination that already has FX releases its sounding notes: the audio thread flushes (all-notes-off) any destination whose FX configuration changed, on the next block. For keys held while you change FX:

  • The very first setMidiFx call on a destination with no active FX flushes nothing, since there is no live configuration to replace yet.
  • Every later swap releases the sounding notes automatically, so no follow-up panic is needed. If a swap must not audibly cut a held note, time it for a gap between notes rather than mid-sustain.

The call publishes an immutable configuration from the control thread and the audio thread adopts it at the next block boundary, so it may run while engine processing is active.

MIDI panic and stuck-note recovery ​

A stuck note is a note-on whose matching note-off never arrived — a yanked cable, a dropped Bluetooth packet, an FX swap that ate the off. The cure is a MIDI panic: an all-notes-off that releases every sounding voice.

typescript
engine.pushMidiPanic();   // immediate; or pass a renderFrame to schedule it

Panic is realtime-safe and cheap — wire it to a visible "panic" button in any instrument UI. The Web MIDI bridge does not auto-panic on disconnect, so if you handle hot-unplug yourself, send a panic when a port you were playing goes away.

Note-offs are not dropped under load: one that a full MIDI output refuses is retried every block, and a full MIDI-FX queue releases the note at once and withdraws its pending note-on. Scheduled MIDI lands on the same frame whatever block size the host runs, including MIDI-FX output, releases at a clip's end, and events after a loop wrap.

The browser Web MIDI bridge ​

A few wire-format terms

UMP (Universal MIDI Packet) is the MIDI 2.0 message format; the bridge accepts it as well as classic MIDI 1.0 bytes. SysEx (System Exclusive) is a free-form, manufacturer-specific message — used for things like a GS Reset — and browsers gate it behind a separate permission. RPN / NRPN ((non-)registered parameter numbers) address extra parameters via CC, for example RPN 0 sets the pitch-bend range.

In the browser, bindWebMidi(engine, options) does the plumbing: it requests MIDI access, enables the engine's live input source, attaches listeners to every matching input port, parses incoming bytes (including running status and one-data-byte messages), and queues them onto the engine with sample timestamps. A Web MIDI Uint32Array payload, or a payload whose first value is above 0xff, is read as a stream of UMP packets and split by each packet's message type. When the supplied engine has pushMidiInputUmp, each complete one-to-four-word channel-voice packet keeps its original MIDI 2.0 width; MT 0x3 and MT 0x5 data packets are left for a SysEx path. If the engine only supplies the convenience methods, MIDI 2.0 channel voice is reduced to the matching 7-bit note/CC/pressure or 14-bit pitch-bend method.

typescript
import { init, RealtimeEngine, isWebMidiAvailable, bindWebMidi } from '@libraz/libsonare';

await init();
if (!isWebMidiAvailable()) {
  // navigator.requestMIDIAccess is missing — fall back to an on-screen keyboard.
}

const engine = new RealtimeEngine({ sampleRate: 48000, maxBlockSize: 128 });
engine.setSynthInstrument(0, { preset: 'sawLead' });

const binding = await bindWebMidi(engine, {
  destinationId: 0,        // engine MIDI destination to play (default 0)
  group: 0,                // UMP group for MIDI 1.0 events (default 0)
  // inputIds: ['<port-id>'],  // restrict to specific ports; omit = all connected
  sysex: false,            // request SysEx-capable access (default false)
  software: true,          // request software ports where supported (default true)
  ccBindings: [
    { ccNumber: 1, channel: 0, paramId: 42, minValue: 0, maxValue: 1 },
  ],
  // Optional: return a block-relative offset in samples for each event time.
  // Only the thread that renders can compute it; see "Why timestamp -> sample mapping matters".
  // A worklet engine takes `context` instead (exclusive with this option).
  // timestampToOffsetInBlockSamples: (eventTimeMs) => offset,
  onInputsChanged: (inputs) => {
    // Called on hot-plug after the helper rebinds matching ports.
    console.log('MIDI inputs:', inputs.map((i) => `${i.name} (${i.state})`));
  },
});

// binding.inputs()  -> WebMidiInputInfo[] { id, name, manufacturer, state }
// binding.access    -> the underlying MIDIAccess object, if you need raw control

What each option does:

  • destinationId / group — which engine destination receives the live events, and the UMP group stamped on MIDI 1.0 channel-voice events.
  • inputIds — restrict binding to specific port ids (from binding.inputs()); omit or pass an empty array to bind every connected input.
  • sysex / software — passed straight to navigator.requestMIDIAccess. SysEx access usually triggers a separate permission prompt; software requests software-synth ports where the platform offers them.
  • ccBindings — bindMidiCc mappings applied before any port connects, so the very first knob move is already routed. Register the target parameters with addParameter(...) first.
  • onInputsChanged — fires on hot-plug (MIDIAccess statechange) after the helper has rebound matching ports, with the fresh port list.

Why timestamp → sample mapping matters ​

The two clocks don't match. Web MIDI tags each message with a time in milliseconds (the page clock, DOMHighResTimeStamp), but the engine schedules events by sample frame. timestampToOffsetInBlockSamples(eventTimeMs) is the bridge between them: it converts a message time into the offsetInBlockSamples value the engine queues. That value is an offset, in samples, from the start of the render block that picks the event up, not a position on an absolute clock. An offset past the end of the block is clamped to the block's last frame. Measured with a 128-frame block, an offset of 40 starts the note at frame 41, while a page-clock time converted straight to samples (480000 after ten seconds) produces nothing until the block's final frame, so every event of a fast run lands on the same frame.

Why bother? Get the conversion right and tightly-timed passages (chords, fast runs) land on the exact frame you played them. Omit it, and every event is queued at sample 0 of the next block, so timing snaps to block boundaries: 2.7 ms steps at 128 frames and 48 kHz, 10.7 ms at 512 frames. That is fine for casual playing and audible on a fast run.

Only the rendering thread can compute an offset. The offset is relative to the block the engine renders next, and only the thread that renders knows which block that is. With the engine in an AudioWorklet, the normal browser setup, the main thread does not: a posted call takes time to arrive, and by then the block the main thread had in mind has been rendered. Its offset then points past the block the event actually lands in, gets clamped to that block's last frame, and the events cluster as described above. So timestampToOffsetInBlockSamples is for a host that renders on the same thread that calls bindWebMidi. The worklet engine takes a time instead of an offset, as the next section describes.

Precise timing on the AudioContext clock ​

Pass the AudioContext as context and bindWebMidi stops working with offsets. For each event it reads context.getOutputTimestamp(), moves the event's page-clock time onto the context clock, adds a scheduling delay, and pushes the event with { contextTimeSec }. The registered engine processor turns that time into a render frame at the head of each quantum, so the event starts on its own sample and a fast run keeps its spacing instead of bunching at block heads.

typescript
const binding = await bindWebMidi(engine, {
  context,                   // the AudioContext the SonareEngine renders in
  // scheduleAheadSec: 0.005, // default: baseLatency + outputLatency + two render quanta
});

// Later: how many events arrived after their frame had been rendered.
console.log('late MIDI events:', await engine.lateMidiEventCount());
  • scheduleAheadSec: how far each event is delayed on the context clock. Omitted, it is the context's baseLatency + outputLatency plus two render quanta (2 × 128 / 48000 s, about 5.3 ms at 48 kHz), read again for every event; a latency the browser does not report counts as 0. 0 is allowed. A smaller value answers sooner and plays more events late; a larger one keeps every event on its sample at the cost of the delay.
  • Late events: an event whose frame has already been rendered when it reaches the processor plays at the start of the next block and is counted. await engine.lateMidiEventCount() returns the count since the engine was created. A count that keeps climbing while you play means the delay is too short for this machine.
  • Pushing directly: the pushMidiInput* methods of SonareEngine take the same option as a trailing argument, for example engine.pushMidiInputNoteOn(0, 0, 60, 100, undefined, { contextTimeSec: context.currentTime + 0.05 }). It is exclusive with offsetInBlockSamples; giving both throws a TypeError.
  • Which engine: context needs an engine whose pushes take contextTimeSec, which is the one that has lateMidiEventCount: the AudioWorklet SonareEngine. Handing bindWebMidi a main-thread RealtimeEngine with context throws a TypeError, as does combining context with timestampToOffsetInBlockSamples.

Measured with the context clock 5 s ahead of the engine's render frames, as it is once a page has been open a while: an event due 40 frames into a block starts on exactly that frame, and an event whose frame had already been rendered starts on the first frame of the next block and moves lateMidiEventCount() from 0 to 1.

Web MIDI to the registered engine processor
portMIDI event(page-clock ms)Main thread: bindWebMidi places it onthe context clock (contextTimeSec)Processor: maps thetime to a render frameStarts on that frame(late: next block start)
The processor knows which render frame each context time falls on, so a live event keeps its own sample.

Lifecycle ​

bindWebMidi returns a WebMidiBinding. When you are done, call binding.destroy() (or using): it removes the statechange listener, detaches every port listener, and calls engine.clearMidiInputSource(). It does not destroy the engine; release that separately with engine.destroy().

Browser support ​

Web MIDI support is uneven, so check at runtime with isWebMidiAvailable() and degrade gracefully:

  • Chrome and Edge (desktop) — full Web MIDI, including hot-plug and SysEx (behind a permission prompt). The primary target.
  • Firefox — has shipped Web MIDI; SysEx and add-on requirements have varied over time, so feature-detect rather than assume.
  • Safari — historically did not expose navigator.requestMIDIAccess; support has been changing, so do not assume it is present. Always gate on isWebMidiAvailable() and offer an on-screen keyboard as the alternate input path.

Recipe: a USB keyboard plays a synth in the browser ​

A runnable path from "keyboard plugged in" to "sound out of the speakers". It takes two files because the work spans two threads:

  • Audio thread — the engine's registered AudioWorklet processor renders a block every render quantum. The engine must render here: on the main thread, process(...) is not called by the audio callback, so it would stay silent.
  • Main thread — owns the Web MIDI access (bindWebMidi) and a SonareEngine, which forwards each call to the processor through the node's port.

SonareEngine implements every method bindWebMidi calls: setMidiInputSource, bindMidiCc, clearMidiInputSource and the pushMidiInput* family, pushMidiInputUmp included. It is handed to bindWebMidi as it is, and MIDI 2.0 packets keep their width.

Audio thread: the processor module ​

An AudioWorkletGlobalScope cannot fetch, so the processor module takes the module factory from @libraz/libsonare/module, and the main thread passes the .wasm bytes.

typescript
// processor.ts — the module given to audioWorklet.addModule()
import moduleFactory from '@libraz/libsonare/module';
import { type ModuleFactory, registerSonareRealtimeEngineWorkletProcessor } from '@libraz/libsonare/worklet';

(globalThis as { SonareEmbindModuleFactory?: ModuleFactory }).SonareEmbindModuleFactory = moduleFactory;
registerSonareRealtimeEngineWorkletProcessor();

Main thread: Web MIDI drives the engine ​

SonareEngine keeps an offline mirror of the engine on the main thread, so the main thread calls init() before creating it.

typescript
import { bindWebMidi, init, isWebMidiAvailable } from '@libraz/libsonare';
import { SonareEngine } from '@libraz/libsonare/worklet';
// `?url` and `?worker&url` are how Vite imports an asset URL; use your bundler's equivalent.
import wasmUrl from '@libraz/libsonare/wasm?url';
import processorUrl from './processor.ts?worker&url';

async function startKeyboardSynth() {
  if (!isWebMidiAvailable()) {
    throw new Error('Web MIDI not available — use an on-screen keyboard instead.');
  }

  // Call this from a user gesture so the context runs.
  const context = new AudioContext({ latencyHint: 'interactive' });
  await init();
  const wasmBinary = await (await fetch(wasmUrl)).arrayBuffer();
  const engine = await SonareEngine.create(context, { moduleUrl: processorUrl, wasmBinary, numChannels: 2 });
  engine.node.connect(context.destination);
  engine.setSynthInstrument(0, { preset: 'sawLead' }); // MIDI destination 0

  const binding = await bindWebMidi(engine, {
    destinationId: 0,
    context, // place each event on the context clock, to the sample
    onInputsChanged: (inputs) =>
      console.log('keyboards:', inputs.map((i) => i.name).join(', ')),
  });

  // Pressing a key on the USB keyboard now sounds the 'sawLead' patch.

  return {
    stop() {
      binding.destroy(); // detach MIDI ports; calls engine.clearMidiInputSource()
      engine.destroy();
      void context.close();
    },
  };
}

context places each event on the AudioContext clock, as described in "Precise timing on the AudioContext clock" above, so a chord or a fast run plays with the spacing it was played with. await engine.lateMidiEventCount() reports how many events arrived too late to keep their sample.

Browser gestures and cleanup

An AudioContext must be created/resumed from a user gesture (a click), and most browsers only prompt for MIDI access from a secure context. Pair bindWebMidi with binding.destroy(), and when the page tears down release the engine with engine.destroy() and close the AudioContext.

On other runtimes ​

The live-MIDI engine API is not browser-only. The Node native and Python bindings expose the same RealtimeEngine input methods — only the Web MIDI bridge itself is browser-specific (it depends on navigator.requestMIDIAccess). In Python the names follow the snake_case convention:

python
import libsonare as sonare

engine = sonare.RealtimeEngine(sample_rate=48000, max_block_size=128)
try:
    engine.set_synth_instrument("sawLead", destination_id=0)
    engine.set_midi_input_source(0)
    engine.push_midi_input_note_on(0, 0, 60, 100, 0)   # group, channel, note, velocity, offset_in_block_samples
    engine.push_midi_input_cc(0, 0, 1, 64, 0)
    engine.push_midi_input_note_off(0, 0, 60, 0, 0)
    out = engine.process([[0.0] * 128, [0.0] * 128])   # non-zero once the note sounds
finally:
    engine.close()

To feed those engines from real hardware, read MIDI with a platform library (for example CoreMIDI or ALSA bindings) and call the same push_midi_input_* methods — the timestamp-to-sample mapping is yours to supply, just as timestampToOffsetInBlockSamples is in the browser.

Experimental native macOS backends

A C++ source build can opt into native macOS host backends behind the off-by-default BUILD_COREAUDIO, BUILD_COREMIDI, and BUILD_AU_HOST CMake options — a CoreAudio output, a CoreMIDI input/output, and an Audio Unit instrument host. They add no C-ABI API and ship in no published package (npm / PyPI / WASM), so they are a macOS-only, source-build opt-in that may still change.

A note on microphone input ​

Live MIDI is control input — it tells the engine what to play. Audio input (a microphone, an instrument through an interface) is a different path: bindMicrophoneInput(context, engine, options) routes captured audio into the engine for monitoring and recording. The two are independent and can run at once. See Recording and Takes.