Edit MIDI Clips and Import or Export SMF Files
This page covers MIDI in a project: editing a clip's events (building, validating, routing, and baking MIDI-FX), key and chord annotations, assist sidecars, tempo detection, SMF import and export, rendering, and external MIDI gear. The task pages below go deeper on transcription, MIDI 2.0, and persistence.
| Task | Guide |
|---|---|
| Turn audio into note events | Audio to MIDI |
| Edit measured notes inside audio | Note Editing in Audio |
| Keep MIDI 2.0 values and UMP words | MIDI 2.0, UMP, and Clip Files |
| Compile, save, load, rebind audio, import stems | Compile, Save, and Load Projects |
Edit MIDI clips
A MIDI clip is a symbolic event list on a project timeline. This section covers the clip editing path: construct channel-voice events, replace a clip, check note pairs, route captured input, and choose between a non-destructive MIDI-FX chain and a baked result. For full-resolution MIDI 2.0 UMP builders and live multi-word messages, see MIDI 2.0, UMP, and Clip Files.
MIDI events are not audio
setMidiEvents changes the stored note and controller events. It does not render or alter PCM. Bind an instrument and bounce the project when the clip should become sound; see Rendering audio and Bouncing Projects.
MIDI content
A MIDI clip holds a flat event list. Build events with the midi* packer functions (which produce the canonical MIDI 1.0 words) and replace the clip's list with setMidiEvents.
Numbers start at 0
Every packer takes (ppq, group, channel, …), and the numbers are the raw values on the wire, counted from 0:
| Argument | Range | What a MIDI device or GM chart calls it |
|---|---|---|
group | 0–15 | The UMP group, a bank of 16 channels in MIDI 2.0 packets. Use 0 unless you route several groups |
channel | 0–15 | MIDI channels 1–16; channel 9 is the GM drum channel 10 |
program | 0–127 | Programs 1–128; 4 is GM program 5, Electric Piano 1 |
note | 0–127 | 60 is middle C (C4) |
setMidiEvents discards the clip's SysEx
A clip's SysEx payloads (a GS Reset, a GS setup block made of manufacturer SysEx "Data Set" messages) live beside its event list, reached through a handle that ProjectMidiEvent does not carry. importSmf() keeps them, exportSmf() writes them back byte for byte, toJson() carries them, and an offline bounce realizes them: a GS insertion-effect type-select embedded in an imported SMF changes the rendered audio. setMidiEvents() replaces the list and leaves nothing referring to the payloads, so one call drops every frame, and there is no read-back entry point to save them through first. A caller that must preserve a GS setup block edits the exported file rather than the clip's event list.
import { Project, init, midiNoteOff, midiNoteOn } from '@libraz/libsonare';
await init();
const project = new Project();
project.setSampleRate(48000);
const { clipId: midiClip } = project.addMidiClip(0, 4);
project.setMidiEvents(midiClip, [
midiNoteOn({ ppq: 0, group: 0, channel: 0, note: 60, velocity: 100 }),
midiNoteOff({ ppq: 2, group: 0, channel: 0, note: 60 }),
midiNoteOn({ ppq: 2, group: 0, channel: 0, note: 64, velocity: 100 }),
midiNoteOff({ ppq: 3.75, group: 0, channel: 0, note: 64 }),
]);
project.setProgram(midiClip, 4); // GM program (e.g. 4 = electric piano)
// Keep `project` for the following edit steps; call project.destroy() when done.import libsonare as sonare
project = sonare.Project()
project.set_sample_rate(48000)
midi_clip = project.add_midi_clip(0.0, 4.0).clip_id
project.set_midi_events(midi_clip, [
sonare.midi_note_on(0.0, 0, 0, 60, 100), # (ppq, group, channel, note, velocity)
sonare.midi_note_off(2.0, 0, 0, 60),
sonare.midi_note_on(2.0, 0, 0, 64, 100),
sonare.midi_note_off(3.75, 0, 0, 64),
])
project.set_program(midi_clip, 4) # GM program (e.g. 4 = electric piano)
# Keep `project` for the following edit steps; call project.close() when done.A clip like this, drawn as a piano roll and played:
In Python, midi_note_on(...) and midi_note_off(...) are module-level packers that each return a frozen ProjectMidiEvent(ppq, word0, word1) record; set_midi_events accepts any sequence of those records.
setProgram takes an optional options object: setProgram(clipId, program, { bank, group, channel }). Omit bank and no Bank Select is emitted; pass { msb, lsb } (each 0 to 127) to emit a Bank Select ahead of the program change. A bank that is not an { msb, lsb } object is refused with a TypeError. group and channel pick the UMP (Universal MIDI Packet) group and channel the program change is written on, and both default to 0. Python spells the same call set_program(clip_id, program, bank_msb=None, bank_lsb=None, group=0, channel=0); pass the two bank halves together or neither.
ppq is in quarter notes, not ticks
The ppq argument is a position in quarter notes (a float), not a MIDI tick count. midiNoteOn({ ppq: 1, … }) is one quarter note in; midiNoteOn({ ppq: 0.5, … }) is an eighth note in. Despite the name, it is not 480-ticks-per-quarter: midiNoteOn({ ppq: 480, … }) schedules the note 480 quarter notes (120 bars) away, almost always far past your render window, so it silently never sounds. If you are converting from a tick-based source (an SMF at 480 PPQ, say), divide by the source's ticks-per-quarter first; see Timing: ticks and PPQ. The same unit applies to addMidiClip(startPpq, lengthPpq) and every clip/automation position on this page, and every one of them is limited to the PPQ range.
Every packer takes one request object and returns one or more MIDI 1.0 UMP events ready to drop into a setMidiEvents list:
| Packer | Signature | Event |
|---|---|---|
| Note on | midiNoteOn({ ppq, group, channel, note, velocity }) | Note-on |
| Note off | midiNoteOff({ ppq, group, channel, note, velocity? }) | Note-off |
| Control change | midiCc({ ppq, group, channel, controller, value }) | CC |
| Program change | midiProgram({ ppq, group, channel, program }) | Program-change |
| Bank + program | midiBankProgram({ ppq, group, channel, program, bank }) | Bank-select + program-change (returns multiple events) |
| Poly pressure | midiPolyPressure({ ppq, group, channel, note, pressure }) | Per-note aftertouch |
| Channel pressure | midiChannelPressure({ ppq, group, channel, pressure }) | Channel aftertouch |
| Pitch bend | midiPitchBend({ ppq, group, channel, bend }) | Pitch-bend; bend is unsigned 14-bit (0..16383, center 8192); out-of-range throws RangeError |
The event-level midiProgram(...) packer places a program-change word inside a clip's event list; it is distinct from the clip-level project.setProgram(midiClip, program) convenience shown above, which sets the clip's default program directly.
validateMidiNotes
Before bouncing, check a MIDI clip for hanging notes: a note-on with no matching note-off (or vice versa) plays a stuck note. validateMidiNotes pairs note-ons and note-offs FIFO per channel + note within the clip's playback window and reports the result. A note cut by the clip end or a loop boundary is closed with a note-off there, so a note that runs past the clip still validates as a matched pair. A note-on that never had a note-off is still reported.
const check = project.validateMidiNotes(midiClip);
// { ok: true, unmatchedNoteOns: 0, unmatchedNoteOffs: 0 }
if (!check.ok) {
console.warn(`hanging notes: ${check.unmatchedNoteOns} on / ${check.unmatchedNoteOffs} off`);
}check = project.validate_midi_notes(midi_clip)
# check.ok, check.unmatched_note_ons, check.unmatched_note_offs
if not check.ok:
print(f"hanging notes: {check.unmatched_note_ons} on / {check.unmatched_note_offs} off")Route a captured MIDI stream
midiRouteEvents({ events, ...config }) is a module function that runs a captured ProjectMidiEvent stream through the native MidiRouter (filter / remap / channel-thru), the same router the live runtime uses, and returns a ProjectMidiRouteResult. Use it to pre-filter or remap recorded input offline before building clips.
const routed = midiRouteEvents({
events: capturedEvents,
filterGroup: 0, // keep group 0 only (omit = any)
filterChannel: 9, // keep channel 9 (the drum channel)
remapChannel: 0, // rewrite surviving events onto channel 0
thru: true, // pass matching events through
});
// routed.events -> ProjectMidiEvent[]
// routed.overflowed -> true if the router buffer dropped events
// routed.overflowCount-> number of dropped events
project.setMidiEvents(midiClip, routed.events);Config fields are all optional and camelCase in JS/WASM (filterGroup, filterChannel, remapChannel, thru); an omitted filter field means "any", and an omitted remapChannel leaves the channel unchanged. Python calls the module-level midi_route_events(events, config) with snake_case keys (filter_group, filter_channel, remap_channel, thru), each 0 to 15 or absent. The helper ships across WASM, Node, and Python. Pair it with the offline CC learn flow below.
Learn a CC and turn it into automation
The C entry sonare_midi_cc_learn validates the entire event list, including events after a learnable prefix. A malformed event returns SONARE_ERROR_INVALID_PARAMETER and clears the output binding.
For an offline "wiggle a knob, capture which CC moved" flow, midiCcLearn({ events, paramId, ... }) scans a captured event stream, picks the controller that moved, and returns a binding descriptor for the parameter paramId (or null when nothing qualifies). midiCcToBreakpoint({ bindings, event }) then turns a CC event into an automation breakpoint (or null when no binding maps it), and midiParamToCc({ bindings, paramId, unitValue, group, ppq }) turns a parameter value back into a CC event. All three work on captured ProjectMidiEvent data, not on the live engine; for live CC-to-parameter binding see MIDI input.
const cc = (ppq: number, value: number) =>
midiCc({ ppq, group: 0, channel: 0, controller: 1, value }); // CC1 on channel 0
const events = [cc(0, 10), cc(0.5, 100)];
const binding = midiCcLearn({ events, paramId: 42, minMovement: 20 });
// { ccNumber: 1, channel: 0, kind: 'controlChange7', paramId: 42, minValue: 0, maxValue: 1, ... }
const point = midiCcToBreakpoint({ bindings: [binding!], event: events[1] });
// { ppq: 0.5, value: 0.787, curveToNext: 'linear' }
const back = midiParamToCc({ bindings: [binding!], paramId: 42, unitValue: 0.5, group: 0, ppq: 1 });
// a CC event at ppq 1cc = lambda ppq, value: sonare.midi_cc(ppq, 0, 0, 1, value) # CC1 on channel 0
events = [cc(0.0, 10), cc(0.5, 100)]
binding = sonare.midi_cc_learn(events, 42, min_movement=20)
point = sonare.midi_cc_to_breakpoint([binding], events[1]) # an AutomationPoint, or None
back = sonare.midi_param_to_cc([binding], 42, 0.5, 0, 1.0) # a ProjectMidiEvent, or NoneminMovement (Python min_movement) is an integer from 0 through 127 (default 0), measured in 7-bit CC units (a 14-bit pair is a low-numbered CC 0..31 plus the CC 32 numbers above it, explained in MIDI Basics; RPN/NRPN sequences are the parameter-number writes described there too); a value outside that range throws. With 0, the first observed standalone controller value binds immediately; a low-numbered CC (0..31) is held until the next message so it can still form a 14-bit pair. With a positive threshold, the controller must move by at least that many 7-bit units from its first value on the same UMP group and channel. MIDI 2.0 32-bit CC values are downscaled to those 7-bit units. The threshold applies only to standalone 7-bit controllers; 14-bit pairs and RPN/NRPN sequences are assembled without this gate.
Bake a MIDI-FX chain into a clip
A MIDI-FX chain (transpose, velocity curve, humanize, and so on) normally sits as a non-destructive layer over a clip's events. bakeMidiFx does the opposite: it runs the chain once and rewrites the clip's stored MIDI events with the result, so the transformed notes become the clip's real content. Bake when you want to freeze an effect into the arrangement; keep it non-destructive when you still want to tweak it.
project.bakeMidiFx({ clipId: midiClip, config: { transposeSemitones: 12 } }); // up one octave; the events are transposed in placeThe result always carries what the bake changed; an editor that needs to preserve a selection or annotation through the rewrite sets withSourceIndex. sourceIndex has one entry per transformed event in canonical order: it always names the input event the output derives from, with an index in 0..inputCount-1. A chord or arpeggiator can produce several events with the same source index.
const config = { arpeggiatorIntervals: [0, 4, 7], arpeggiatorStepPpq: 0.25 };
const count = project.previewMidiFxCount({ clipId: midiClip, config });
const { sourceIndex } = project.bakeMidiFx({
clipId: midiClip,
config,
withSourceIndex: true,
});previewMidiFxCount(...) runs the same deterministic transform without changing the project, so its result is the exact number of events the following bake produces. Without withSourceIndex the result is an empty object. In Python, project.preview_midi_fx_count(clip_id, config) returns the count and project.bake_midi_fx(clip_id, config, with_source_index=True) returns the source indexes as an int32 array (without the flag it returns None); config is a mapping with the same camelCase keys.
The config is an object whose stages are keyed by their parameters: include a stage's keys to enable it, omit them to skip it. An unknown key (a snake_case spelling included) is refused with a SonareError naming it, and the clip is left unchanged:
| Stage | Keys |
|---|---|
| Transpose | transposeSemitones |
| Velocity curve | velocityScale, velocityOffset, velocityGamma (>0); see below |
| Quantize | quantizePpq (>0), quantizeStrength (0–1, default 1) |
| Humanize | humanizePpq (>=0), humanizeVelocity (0–127), seed (non-negative integer); deterministic timing/velocity jitter |
| Chord | chordIntervals (array of semitone offsets, 1-8 entries) |
| Arpeggiator | arpeggiatorIntervals (array of semitone offsets, 1-16 entries), arpeggiatorStepPpq (>0), arpeggiatorGatePpq (defaults to the step length, capped to it) |
The velocity curve applies to note-ons only, in this order: normalize the velocity to 0..1, raise it to velocityGamma, multiply by velocityScale, add velocityOffset (in 7-bit velocity units), then round and clamp to 1..127 (a note-on never falls to 0). As a formula, v' = clamp(127 · (v/127)^gamma · scale + offset). A gamma above 1 pulls soft notes down and leaves loud ones, and a gamma below 1 lifts soft notes. MIDI 2.0 note-ons are shaped in their full 16-bit range rather than rounded to 7 bits first.
Quantize moves events toward a grid of quantizePpq quarter notes (0.25 is a sixteenth-note grid), counted from the clip's own start. Each note-on moves toward its nearest grid line by quantizeStrength times the distance (1 lands on the line, 0.5 goes halfway), and its note-off moves by the same amount, so note lengths are kept. Controllers and other events keep their position. With a sixteenth grid at full strength, a note from 0.3 to 0.9 becomes 0.25 to 0.85.
chordIntervals is capped at 8 entries and arpeggiatorIntervals at 16; an empty array, or one past either limit, makes bakeMidiFx throw a SonareError naming the key rather than silently truncating.
// Turn each held note into a three-step up-arpeggio, one sixteenth per step.
project.bakeMidiFx({
clipId: midiClip,
config: { arpeggiatorIntervals: [0, 4, 7], arpeggiatorStepPpq: 0.25, arpeggiatorGatePpq: 0.2 },
});Because the rewrite is destructive, it is an undoable edit like any other, and undo() restores the original events.
Key and chord annotation write-back
A project can carry musical annotations, the key regions and chord symbols that an analyzer produced, so they travel with the arrangement and survive save/load. Both streams are replace-in-full and undoable.
project.annotateKeys([
{ startPpq: 0, endPpq: 16, tonicPc: 0, mode: 'major' }, // C major (tonicPc 0)
]);
project.annotateChords([
{ startPpq: 0, endPpq: 4, rootPc: 0, quality: 'major', romanNumeral: 'I' },
{ startPpq: 4, endPpq: 8, rootPc: 7, quality: 'major', romanNumeral: 'V' },
]);project.annotate_keys([
{"start_ppq": 0.0, "end_ppq": 16.0, "tonic_pc": 0, "mode": "major"}, # C major
])
project.annotate_chords([
{"start_ppq": 0.0, "end_ppq": 4.0, "root_pc": 0, "quality": "major", "roman_numeral": "I"},
{"start_ppq": 4.0, "end_ppq": 8.0, "root_pc": 7, "quality": "major", "roman_numeral": "V"},
])In Python both annotate_keys and annotate_chords take mappings with the same fields as the WASM objects (snake_case keys); an unknown key is refused by name, and a tuple is a TypeError.
The fields take small fixed sets:
- Pitch class (
tonicPc,rootPc,slashBassPc): an integer0..11with C = 0, C#/Db = 1, … B = 11; omit the field when the pitch is unknown (255is refused with aRangeError). - Key mode (
mode):'unknown'(the default),'major','minor','dorian','phrygian','lydian','mixolydian'or'locrian'. UsekeyModeFromAnalysisto map an analysis mode. - Chord quality (
quality):'unknown'(the default),'major','minor','diminished','augmented','dominant','halfDiminished'or'suspended'.extensionslists scale degrees (7,9,13, or2/4for a suspension; at most 32) that distinguish variants within a family (see Chord Recognition for detector qualities).
So { tonicPc: 0, mode: 'major' } is C major and { rootPc: 7, quality: 'major' } is a G major chord. A number where a token belongs is a TypeError, and an unknown token a RangeError. romanNumeral is optional; omit it when no numeral is known, because an explicit empty string is refused.
Detector qualities fold into a family plus extensions
The analysis qualities are finer than the arrangement's eight: dominant7 becomes { quality: 'dominant', extensions: [7] }, halfDim7 becomes { quality: 'halfDiminished', extensions: [7] } and sus4 becomes { quality: 'suspended', extensions: [4] }. Do not map them by hand: the next section applies the library's own table.
Convert a detected chord or key
chordSymbolFromAnalysis(chord) (Python chord_symbol_from_analysis, C sonare_chord_symbol_from_analysis) turns an analysis chord into { rootPc, quality, extensions, slashBassPc } (Python snake_case keys), the same conversion the library applies when it builds a harmonic timeline. The root is kept as given, and slashBassPc is absent when the bass is the root. keyModeFromAnalysis(mode) (key_mode_from_analysis, sonare_key_mode_from_analysis) returns the annotation mode token for an analysis mode name (a number is a TypeError). Times are not converted; place the result with startPpq / endPpq. An unrecognized value is a RangeError (Python SonareValueError) naming the field, and a non-object chord is a TypeError.
const bpm = 120; // the project's constant tempo
const toPpq = (seconds: number) => (seconds * bpm) / 60; // assumes bpm counts quarter notes
const { chords } = detectChords(samples, sampleRate); // startSec / endSec are in seconds
project.annotateChords(
chords.map((c) => ({ startPpq: toPpq(c.startSec), endPpq: toPpq(c.endSec), ...chordSymbolFromAnalysis(c) })),
);
project.annotateKeys([
{ startPpq: 0, endPpq: 16, tonicPc: key.root, mode: keyModeFromAnalysis(key.mode) },
]);toPpq here assumes one constant tempo whose BPM counts quarter notes (in 6/8 a written tempo often counts dotted quarters, so convert it first). Under a tempo map with several segments or ramps, convert each time with the formulas in Converting seconds, samples, and PPQ.
What the analyzers report before it becomes an annotation is on Chord Recognition and Key Detection.
Assist sidecars
An assist sidecar is an opaque, undoable per-project metadata blob: a place to stash an AI-assist suggestion, a tooling payload, or any binary annotation that should travel with the arrangement. Each sidecar is keyed by a module id plus a target scope (a track id and a PPQ region), and the whole store serializes under the project JSON assistSidecars key, so it survives toJson() / fromJson() round-trips.
const payload = new TextEncoder().encode(JSON.stringify({ suggestion: 'tighten chorus' }));
project.setAssistSidecar({
moduleId: 'my-assistant', // must be non-empty
schemaVersion: 1,
targetTrackId: 0, // 0 = project scope
regionStartPpq: 0,
regionEndPpq: 16,
payload, // Uint8Array (copied)
});
project.assistSidecars(); // [{ moduleId, schemaVersion, targetTrackId,
// regionStartPpq, regionEndPpq, payload }, ...] in stable project orderA sidecar that shares the same moduleId + targetTrackId + region scope as an existing one replaces it; otherwise it is appended. targetTrackId 0 means project scope. Because the write is an undoable edit, undo() / redo() reverse it.
The descriptor form above is the WASM and Node JavaScript API: setAssistSidecar takes one input object, and assistSidecars() reads every sidecar at once (pick one by index from the array). Python uses set_assist_sidecar(module_id, payload, *, schema_version=0, target_track_id=0, region_start_ppq=0.0, region_end_ppq=0.0) (a mapping descriptor is a TypeError), read back with assist_sidecars(). The C ABI remains positional as sonare_project_set_assist_sidecar(...), with the matching count/get/free functions.
Auto-tempo and snap-to-grid
Two helpers align edits to the beat.
autoTempo(samples, sampleRate, options?) detects the tempo from a mono buffer, installs it as the tempo map, and returns { bpm, bpmConfidence, timeSignature }. The detected meter is returned even when applyTimeSignatures is false. analyzeTempo(samples, sampleRate, options?) returns the ranked candidates (primary, half, double) without touching the project; pass a candidate's index as the candidateIndex option (and applyTimeSignatures: true to install the detected meter too) to install that one, with the same scoring options on both calls. Both also take one request object { samples, sampleRate, ...options }. Python passes audio and sample_rate positionally, and all arguments after sample_rate are keyword-only. The scoring options are:
| Option | Default | Meaning |
|---|---|---|
adaptiveTempo | false | Let beat tracking follow a tempo that moves during the take. Leave it off for material recorded to a click. |
tempoUpdateIntervalBeats | native default | Beats of context for the local tempo estimate (only with adaptiveTempo). |
rampThreshold | 0.02 | Relative tempo change at which one segment closes and the next opens. Smaller follows the performance more closely. |
includeOctaveCandidates | true | Rank the half- and double-tempo alternatives alongside the primary. |
With adaptiveTempo on, a drifting performance becomes several tempo segments, which export to SMF as stepped tempo events. The tempo analysis itself is described on Analysis.
snapToGrid(ppq, strength, division) snaps a finite PPQ coordinate in [0, 1e12] to the project grid. strength is 0..1 (1 snaps fully). division is 0 for bars, 1 for beats (default), or the number of subdivisions per beat (4 for sixteenths).
const tempo = project.autoTempo(monoMix, 48000); // { bpm, bpmConfidence, timeSignature }
const { bpm, timeSignature } = tempo; // meter is present even if it was not installed
const snapped = project.snapToGrid(1.2, 1.0); // 1.2 -> 1 (nearest beat)tempo = project.auto_tempo(mono_mix, 48000, adaptive_tempo=True, ramp_threshold=0.05)
bpm = tempo.bpm # also has bpm_confidence and time_signature
snapped = project.snap_to_grid(1.2, 1.0) # 1.2 -> 1 (nearest beat)MIDI interchange: SMF and MIDI 2.0 Clip File
The two interchange formats have different jobs. SMF is the compatible, 480-tick format covered here (ticks and PPQ are explained in Timing: ticks and PPQ). For lossless MIDI 2.0 values use the Clip File (SMF2CLIP), described in MIDI 2.0, UMP, and Clip Files.
Standard MIDI File (SMF)
exportSmf always writes a format-1 (multi-track) file: track 0 carries the tempo + time-signature map, then one MTrk per clip, quantized to 480 ticks per quarter note. The export follows the project's tempo map (a ramp is written as steps, the first tempo at tick 0) and writes every repeat of a looped MIDI clip after a tempo change. Exporting a clip past the SMF size limits fails with InvalidState. At the lower-level SMF exporter, a nonzero PPQN (ticks per quarter note, the same quantity as PPQ) must fit the positive 15-bit range 0x0001–0x7fff; zero selects the default 480. A note cut by its clip's end or a loop boundary is closed with a note-off there, so the file never holds a note that runs past its clip. The importer accepts formats 0 and 1, but a format-0 header must declare exactly one track; format 2, SMPTE timing (a division counted in frames per second instead of ticks per quarter note), and zero PPQN in an input header are rejected.
const smf = project.exportSmf(); // Uint8Array<ArrayBuffer>: SMF format 1, 480 PPQN
// … write `smf` to a .mid file …
const fresh = new Project();
try {
const firstClip = fresh.importSmf(smf); // returns the first added clip id
} finally {
fresh.destroy();
}smf = project.export_smf() # bytes: SMF format 1, 480 PPQN
# … write `smf` to a .mid file …
with sonare.Project() as fresh:
first_clip = fresh.import_smf(smf) # returns the first added clip idNode uses the same calls as the browser package.
SMF represents tempo with discrete Set Tempo events. The exporter writes a tempo ramp as sixteenth-note steps whose durations follow the project tempo map at each step boundary, subject to tick and microsecond quantization. Long ramps use larger steps to limit each ramp to 4096 events. If the first tempo segment starts after PPQ 0, its initial tempo is also written at tick 0, matching the tempo map before that segment. Importing the file restores those steps rather than the original continuous ramp.
exportSmf() and exportClipFile() are declared Uint8Array<ArrayBuffer>, the type the Blob and File constructors accept, so new Blob([project.exportSmf()]) compiles with no intermediate new Uint8Array(...) copy.
On import, a key-signature meta event is kept only when its fifths value is in -7..7 and its minor flag is 0 or 1. A missing or invalid key-signature payload is skipped and counted in skipped_events; parsing of the rest of the track continues.
The importer contains damage locally: if one SMF track has an overlong variable-length quantity or payload, parsing resynchronizes at that track's declared boundary so later valid tracks can still import instead of the whole file failing.
What an SMF round-trips is a performance, and engraved, that same note list is a score. The grand staff below is the notation view of a MIDI clip; press play to hear the events it stores.
An SMF as a reference melody: note targets
See An SMF as a reference melody.
Rendering audio
Editing produces a timeline; rendering turns it into samples. Project bounces offline through bounce(...), which renders audio tracks on their own and makes MIDI tracks audible when you bind instruments with its builtinInstruments, synthInstruments or sf2Instruments option. The full set of render options, instrument binding, SoundFont loading, and the diagnostics reported by a bounce are covered on Project Bounce & Rendering.
To make a MIDI arrangement audible you bind an instrument at render time; the instruments are the native synth and the SoundFont player. For driving a project live from a controller, see MIDI input.
// Audio-only quick render. MIDI tracks are silent here.
const audio = project.bounce({ numChannels: 2 });Sending a track to external MIDI gear
An internal destination renders MIDI through a NativeSynth/SF2 instrument inside libsonare. An external destination skips that instrument and places MIDI 1.0 byte messages in an output queue for your host to send to hardware or another application. libsonare prepares and timestamps the messages; opening the OS/Web MIDI port remains the host's job.
Mark the destination, process audio as usual, then drain the output queue frequently. The raw-engine methods carry the same names across bindings — camelCase in Browser and Node, snake_case in Python:
engine.setMidiDestinationExternal(2, true); // destination 2 now drives external gear
engine.setExternalMidiClockEnabled(true); // optional: clock + start/continue/stop
engine.process([leftBlock, rightBlock]);
for (const event of engine.drainExternalMidi(256)) {
if (event.destinationId === undefined) {
// Clock/transport is broadcast to every external port selected by the host.
for (const output of externalOutputs.values()) output.send(event.bytes);
} else {
externalOutputs.get(event.destinationId)?.send(event.bytes);
}
}// Node exposes the same camelCase raw-engine methods as WASM.
engine.setMidiDestinationExternal(2, true);
engine.setExternalMidiClockEnabled(true);
engine.process([leftBlock, rightBlock]);
for (const event of engine.drainExternalMidi(256)) {
if (event.destinationId === undefined) {
// Forward clock/transport to every open hardware port.
for (const port of externalPorts.values()) port.sendMessage([...event.bytes]);
} else {
externalPorts.get(event.destinationId)?.sendMessage([...event.bytes]);
}
}engine.set_midi_destination_external(2, True) # destination 2 drives external gear
engine.set_external_midi_clock_enabled(True) # optional: clock + start/continue/stop
engine.process([left_block, right_block])
for event in engine.drain_external_midi(256):
if event.destination_id is None:
# Broadcast clock/transport to every open hardware port.
for port in external_ports.values():
port.send_message(list(event.bytes))
else:
port = external_ports.get(event.destination_id)
if port is not None:
port.send_message(list(event.bytes))
# Advisory: a rising count means the queue filled before the host drained it.
dropped = engine.external_midi_dropped_countEach event contains destinationId, renderFrame, and bytes (one lowered MIDI 1.0 message of 1–3 bytes as a Uint8Array; snake_case destination_id / render_frame in Python). Clock and transport messages carry no destination (destinationId is absent, None in Python), which means every external port; channel messages retain their destination id. maxRecords limits the returned messages, not source events, and any remainder stays queued for the next drain. Check externalMidiDroppedCount (the property external_midi_dropped_count in Python): a rising value means the fixed-capacity realtime queue filled before the host drained it.
With the SonareEngine AudioWorklet facade (browser-only), use setMidiDestinationExternal(trackId, true) and subscribe with onMidiOut(callback). The worklet already drains its engine once per render block and posts batches to the main thread, so do not try to call the raw drain as a second consumer:
engine.setMidiDestinationExternal('hardware-lead', true);
const unsubscribe = engine.onMidiOut((events) => {
for (const event of events) {
if (event.destinationId === undefined) {
for (const output of externalOutputs.values()) output.send(event.bytes);
} else {
externalOutputs.get(event.destinationId)?.send(event.bytes);
}
}
});Related
- Project Editing — tracks, clips, tempo, markers, warp, and automation
- MIDI 2.0, UMP, and Clip Files — full-resolution MIDI messages and Clip Files
- Audio to MIDI — transcription onto a constant or project tempo map
- Compile, Save, and Load Projects — timeline compilation and persistence
- MIDI Input — live controller input
- Bouncing Projects — render the timeline and bound instruments