Skip to content

Render a Song Arrangement to WAV Offline ​

Bouncing turns your whole arrangement into a single audio file you can save, play, or analyze. If you have used a DAW, it is the "export" or "render" button; in libsonare it is the Project.bounce* family. The rendering happens offline (all at once, not tied to real time: faster on a light project, slower on a heavy one, and never by playing the song back live) and deterministically: on the same build and runtime, the same project plus the same options always yields exactly the same samples, down to the bit.

A Project holds tracks and clips on a timeline. Audio clips already carry samples, so they render directly. MIDI clips carry events (note-on, note-off), not sound, so they need an instrument to become audible, the same way sheet music needs a player. So the choice of bounce method is really one question: which instrument plays your MIDI?

Bounce pipeline: clips to WAV
PROJECT ON THE TIMELINEMIDI clipsAudio clipsInstrument bindingChannel stripMixer sceneMaster busWAV output
Instrument binding picks NativeSynth, SoundFont, or the built-in synth per MIDI destination; the channel strip then applies trim, EQ, inserts, fader, and pan before the mixer sums everything to the master bus.

The whole pass is computed offline, so the result is reproducible every time.

Positions are in quarter notes

Project positions and clip lengths are expressed in PPQ — quarter notes as a float. ppq: 1 is one quarter note. At 120 BPM one quarter note lasts 0.5 s, so a clip of four quarter notes (lengthPpq: 4) is 2 s. Set the tempo explicitly with setTempoSegments([{ startPpq: 0, bpm: 120 }]) so durations in your bounce are predictable.

Bounce reflects the full mixer, not raw clips

Tracks do not sum naively. Each track renders through its channel strip — trim, EQ, inserts, fader, pan, sends, and buses — via the scene mixer. The bounce is the routed master, exactly what realtime playback would produce.

On a MIDI clip, setClipGain and clip fades scale the bound instrument's output at that clip's destination, not velocity. Project Editing lists how the envelope resolves when several clips share a destination. To move a whole MIDI track's level, use the track fader in the mixer scene.

What You Will Learn ​

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

  • bounce a project of audio clips with plain bounce;
  • make MIDI audible by routing it through the built-in synth, the NativeSynth, or an SF2 player;
  • pass a NativeSynth patch by preset name, va: prefix, or patch object;
  • host your own instrument from JavaScript or Python through the ExternalInstrument protocol;
  • pre-flight a MIDI clip with validateMidiNotes and read the no-instrument compile warning;
  • let the engine auto-derive the render length, and write the result to a WAV file.

Pick the right bounce options ​

Start at the top and only move down when your MIDI needs a richer instrument.

Your projectUseResult
Only audio clips (no MIDI, or MIDI you want silent)bounceRouted audio; MIDI tracks are silent
MIDI you just need to hearbounce with builtinInstruments (builtin_instruments= in Python)Simple oscillator synth
MIDI that needs real instrument characterbounce with synthInstruments (synth_instruments=)Full NativeSynth (subtractive / FM / modal / piano …)
MIDI that should play a SoundFontbounce with sf2Instruments (sf2_instruments=)GS-compatible SF2 player
MIDI played by your own synthbounce with instruments (instruments= in Python)Host-supplied ExternalInstrument

One Project, every runtime

The same Project model and core bounce behavior are exposed through WASM/JS, Node native, and Python. Names follow each language's convention (synthInstruments ↔ synth_instruments). The CLI exposes the project workflow as commands (project bounce, including --synth to route MIDI through the built-in synth, plus SMF/MIDI 2.0 import-export), but not every per-destination instrument binding option is wired there. The arrangement model, the compiler, and the DSP code are the same in every runtime; the bit-exact guarantee below holds within one build and runtime, since another platform can round floating-point math differently in the last bits.

Plain bounce: audio clips ​

bounce compiles the project into a renderable timeline and renders it offline to float audio: planar { channels, sampleRate } in Node and WASM, and ProjectBounceResult in Python. Python's channels is a channels-first (num_channels, frames) float32 array; both runtimes report the project's sample rate. Audio clips play through their channel strips; MIDI clips render silently because no instrument is bound.

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

await init();

const project = new Project();
try {
  project.setSampleRate(48000);
  project.setTempoSegments([{ startPpq: 0, bpm: 120 }]); // predictable durations

  const track = project.addTrack({ kind: 'audio', name: 'tone' });
  project.addClip({
    trackId: track,
    startPpq: 0,
    lengthPpq: 4,              // 4 quarter notes = 2 s at 120 BPM
    channels: [monoSamples],   // planar: one Float32Array per channel
    sampleRate: 48000,
  });

  // Planar stereo: channels[0] is left, channels[1] is right
  const { channels, sampleRate } = project.bounce({ numChannels: 2 });
} finally {
  project.destroy();        // the WASM handle is NOT garbage-collected
}
python
import libsonare as sonare

with sonare.Project() as project:
    project.set_sample_rate(48000)
    project.set_tempo_segments([{"start_ppq": 0.0, "bpm": 120}])  # predictable durations

    track = project.add_track("audio", name="tone")
    project.add_clip(
        track,
        start_ppq=0.0,
        length_ppq=4.0,            # 4 quarter notes = 2 s at 120 BPM
        audio=mono_samples,
        audio_channels=1,
        audio_sample_rate=48000,
    )

    audio = project.bounce(num_channels=2)
    channels = audio.channels         # (2, frames) float32 ndarray; planar
    sample_rate = audio.sample_rate   # the project's rate

Node uses the same calls as the browser package. The examples below show the browser form and the Python equivalent.

Always release the Project

Project, like every embind object, holds a WASM heap handle the JavaScript garbage collector cannot reclaim. Call project.destroy() in a finally block (Python uses project.close()). Leaking handles slowly exhausts WASM memory in long sessions.

Planar and interleaved audio

A Node or WASM bounce is "planar": channels holds one Float32Array per output channel, channels[0] the left. Python's ProjectBounceResult.channels is also planar, as a channels-first (num_channels, frames) ndarray. The WAV writer below interleaves while it writes, so a 2-channel bounce of N frames becomes 2 × N samples in the file.

Bounce options ​

Omit a field to use its default. If supplied, totalFrames, blockSize, and numChannels must be positive. instrumentLatencySamples: 0 specifies no instrument latency. Python takes the same options as keywords:

OptionMeaningDefault
totalFramesRender length in output framesauto-derived (see below)
blockSizeRender block size in frames; any positive value is used as given128
numChannelsOutput channel count: 1, 2, 6, or 8the scene master's width (2 with no master)
instrumentLatencySamplesHost-instrument PDC (plugin delay compensation) fed to the compiler0
builtinInstruments, synthInstruments, sf2Instruments, instrumentsArrays of { destinationId?, instrument } bindings to MIDI destinations (destinationId omitted is destination 0); SF2 bindings may also name a loaded font with soundFontUri; a destination bound twice is refusednone: MIDI tracks render silently

In Python, builtin_instruments=, synth_instruments=, and instruments= take ProjectInstrumentBinding(instrument=..., destination_id=0) records; sf2_instruments= takes ProjectSf2InstrumentBinding(instrument=..., destination_id=0, sound_font_uri=...); controller_profiles= takes ProjectControllerProfileBinding(destination_id=..., preset_name=...); and articulations= takes ProjectArticulationBinding(destination_id=..., channel=..., articulation=...). All four record types are keyword-only. A bounce always uses the project sample rate and returns it as ProjectBounceResult.sample_rate; it does not resample or accept a sample_rate= option.

numChannels cannot exceed the mixer scene's master layout

The master bus processes the bounce at numChannels: a "5.1" master layout allows 6, a "7.1" layout allows 8, and a plain stereo master stays at 1 or 2 (see Bus). A value outside {1, 2, 6, 8}, or wider than the master layout, is refused. Bouncing a surround scene at a narrower numChannels than its master carries folds the extra planes down through the same ITU-R BS.775 downmix (the standard surround-to-stereo fold-down) the realtime engine applies, rather than dropping them.

What is PDC / latency compensation?

Some instruments and effects need a few samples of "lookahead" and so report their audio a little late. PDC (plugin delay compensation) tells the compiler how many samples late an instrument is, so the engine can shift it back into alignment and keep every track in time. If your instrument has no latency, leave this at 0.

Determinism is independent of live state

An offline bounce settles every smoothed gain and effect parameter to its target before rendering, so the result does not depend on where a fader or filter sweep happened to be when you started the render. Bouncing right after a live tweak produces the same samples as bouncing from a freshly loaded project. A bounce, like every offline render, stem bounce and freeze, carries the program output only: an armed PFL/AFL cue (pre-/after-fader listen, a monitoring solo) or a solo monitor state never reaches it.

Omitting the length ​

When totalFrames is omitted the render length is auto-derived from the compiled timeline: the musical end of the arrangement, plus the instrument's release tail, plus the mixer scene's latency and effect tail (a reverb or delay insert keeps sounding after its input stops). A project with content renders without you computing a frame count; an empty project yields an empty buffer. An instrument that reports INT_MAX (2^31 - 1) for tail_samples has an unbounded tail, so an auto-length bounce of a non-empty arrangement is refused; pass a positive totalFrames when you need a bounded window. Pass totalFrames also when you need a fixed-length buffer. A current limitation: an sf2Instruments bounce without totalFrames carries a long silent tail after the last note, and passing totalFrames avoids it. A bounce whose derived length overflows, or whose compiled arrangement does not fit the engine, fails with InvalidState.

The reported latency is rendered ahead and dropped: frame 0 of the bounce is the start of the timeline, so the result needs no manual latency trimming.

With useGmPrograms: true, NativeSynth derives the release bound from the programs and drum note/kit combinations the arrangement actually plays. Unused GM voices do not extend the bounce; the piano soundboard and guitar sympathetic resonance count only after a note has activated them. Before the first note after preparation or reset, or after more than 128 distinct patch/drum combinations have been played, the synth's tail query reports a conservative whole-bank bound.

The drumKit preset (a percussion patch with gmKit on) is bounded the same way: once a note has struck, the tail covers only the kit pieces actually played, so a project that plays one kick over a 2 s clip renders about 2.91 s, not the whole-kit maximum. Before the first note, or after the played set overflows, the tail is the maximum over every piece of the kit.

Bounce MIDI through the built-in synth ​

A MIDI-only project bounced with plain bounce is silent. Route it through the built-in oscillator synth to make it audible with one call. Pass a binding to choose the waveform and envelope, or {} for a default sine patch.

typescript
import { Project, init, midiNoteOff, midiNoteOn } from '@libraz/libsonare';

await init();
const project = new Project();
try {
  project.setSampleRate(48000);
  project.setTempoSegments([{ startPpq: 0, bpm: 120 }]);

  const { clipId } = project.addMidiClip(0, 4);   // MIDI track + clip, 4 quarter notes long
  project.setMidiEvents(clipId, [
    midiNoteOn({ ppq: 0, group: 0, channel: 0, note: 60, velocity: 100 }),   // C4 at the start (PPQ 0)
    midiNoteOff({ ppq: 3, group: 0, channel: 0, note: 60, velocity: 0 }),    // release three quarter notes in (PPQ 3)
  ]);

  // MIDI-only project -> non-silent stereo audio.
  const { channels } = project.bounce({
    numChannels: 2,
    builtinInstruments: [{ instrument: { waveform: 'saw', gain: 0.5 } }],
  });
} finally {
  project.destroy();
}
python
with sonare.Project() as project:
    project.set_sample_rate(48000)
    project.set_tempo_segments([{"start_ppq": 0.0, "bpm": 120}])

    clip = project.add_midi_clip(0.0, 4.0)  # MIDI track + clip (clip.track_id, clip.clip_id), 4 quarter notes long
    project.set_midi_events(clip.clip_id, [
        sonare.midi_note_on(0.0, 0, 0, 60, 100),   # C4 at the start (PPQ 0)
        sonare.midi_note_off(3.0, 0, 0, 60, 0),    # release three quarter notes in (PPQ 3)
    ])

    audio = project.bounce(
        builtin_instruments=[sonare.ProjectInstrumentBinding(
            instrument=sonare.BuiltinSynthConfig(waveform="saw", gain=0.5),
            destination_id=0,
        )],
        num_channels=2,
    )

A BuiltinSynthConfig accepts waveform ('sine', 'saw', 'sawtooth', 'square', 'triangle'), gain, ADSR (attackMs, decayMs, sustain, releaseMs), and polyphony; destination_id on a ProjectInstrumentBinding selects one MIDI destination and defaults to 0. Omit fields to use the defaults. An explicit zero for a numeric field is out of range. Use {} for the default patch. The attackMs, decayMs and releaseMs times are linear ramps over the set time. Pass an array of binding records to render several MIDI destinations; omit the option or pass [] to bind nothing and render silently.

Bounce MIDI through the NativeSynth ​

For real instrument character, synthInstruments routes MIDI through the full NativeSynth: its subtractive, FM, Karplus-Strong, modal, additive, percussion, and piano engines plus the realism layer. There are three ways to specify the instrument:

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

await init();
synthPresetNames();   // ['sine', 'saw', 'square', 'triangle', 'sawLead', 'squareLead', ...]

// 1. A preset name, given through the patch's preset field
const a = project.bounce({
  numChannels: 2,
  synthInstruments: [{ instrument: { preset: 'sawLead' } }],
});

// 2. The same preset with the "va:" routing prefix
const b = project.bounce({
  numChannels: 2,
  synthInstruments: [{ instrument: { preset: 'va:sawLead' } }],
});

// 3. A patch object: a base preset plus shared-control overrides
const c = project.bounce({
  numChannels: 2,
  synthInstruments: [{ instrument: { preset: 'warmPad', cutoffHz: 1200, ampReleaseMs: 600 } }],
});
python
sonare.synth_preset_names()   # ['sine', 'saw', 'square', 'triangle', 'sawLead', 'squareLead', ...]

# 1. A preset name, 2. the same preset with the "va:" routing prefix
a = project.bounce(synth_instruments=[sonare.ProjectInstrumentBinding(
    instrument=sonare.SynthPatch(preset="sawLead"),
)], num_channels=2)
b = project.bounce(synth_instruments=[sonare.ProjectInstrumentBinding(
    instrument=sonare.SynthPatch(preset="va:sawLead"),
)], num_channels=2)

# 3. A patch object: a base preset plus shared-control overrides
c = project.bounce(
    synth_instruments=[sonare.ProjectInstrumentBinding(
        instrument=sonare.SynthPatch(preset="warmPad", cutoff_hz=1200, amp_release_ms=600),
    )],
    num_channels=2,
)

Use synthPresetNames() to discover valid names instead of hardcoding magic strings; unknown names throw. JavaScript bindings put the preset in instrument.preset; Python wraps it in SynthPatch(preset=...). A patch object starts from its preset base (or the default subtractive patch when preset is omitted) and overrides the shared controls — see NativeSynth for the field list. A patch gain must be in [0, 4]; a value outside it, or a non-finite one, is refused by name. Amp and filter decay and release times such as ampReleaseMs are three time constants, about −26 dB at the set time. Pass an array of binding records to bind several destinations; an empty array binds nothing.

Following GM programs instead of pinning one patch

Each SynthPatch bound through synthInstruments may carry useGmPrograms (default false); the destination id (default 0) sits on the binding pair. With useGmPrograms on, MIDI program changes select the matching General MIDI voice per destination while the bound patch stays as the fallback for anything the map does not cover. The sibling spelling use_gm_programs is used on the C ABI and in Python. See Following GM programs instead of pinning one patch for the full explanation and examples.

The piano roll below is exactly this call at work: one MIDI passage routed through synthInstruments and re-voiced live as you switch the preset; the playhead tracks the bounced audio.

MIDI · PIANO ROLLIDLE
A MIDI passage — same notes, any instrument

A three-voice phrase — melody, chords, and bass — drawn as a piano roll. The notes never change; switch the instrument and the engine bounces the exact same MIDI through a different built-in voice. Drag the tempo and the whole sequence speeds up or slows down. Press play to hear the passage; the playhead tracks the audio.

Instrument
Tempo
100 BPM

Deterministic by construction

For a fixed project, options, and patch, bounce with synthInstruments is bit-for-bit reproducible on the same build and runtime. The same is true of every bounce method, which is what makes a bounce safe to snapshot in a test or cache by hash.

Bounce MIDI through a SoundFont ​

bounce with sf2Instruments plays MIDI through a GS-compatible SoundFont player fed by the project's loaded SoundFont. Load the .sf2 bytes first, either into the default slot or a named uri. A binding's soundFontUri selects that loaded font for this bounce; if it names an unloaded URI, the bounce fails with InvalidState. Omit it to use the default; if no default is loaded, uncovered programs fall back to the built-in synth:

typescript
const sf2Bytes = new Uint8Array(await (await fetch('/piano.sf2')).arrayBuffer());
project.loadSoundFont(sf2Bytes, { uri: 'piano' });

// 16 MIDI channels per player; channel 10 drums via bank 128; GS NRPN + SysEx honored.
const { channels } = project.bounce({
  numChannels: 2,
  sf2Instruments: [{ instrument: { gain: 0.5 }, soundFontUri: 'piano' }],
});
python
project.load_sound_font(open("piano.sf2", "rb").read(), uri="piano")

audio = project.bounce(
    sf2_instruments=[sonare.ProjectSf2InstrumentBinding(
        instrument=sonare.Sf2InstrumentConfig(gain=0.5),
        sound_font_uri="piano",
    )],
    num_channels=2,
)

General MIDI, banks, and drums

General MIDI (GM) is the standard 128-instrument set every SoundFont maps to, so program numbers pick the same kind of instrument across files. By convention channel 10 is reserved for drums, addressed as bank 128. NRPN and SysEx are extra MIDI messages for finer or vendor-specific tweaks; you rarely set them by hand.

Programs the selected SoundFont does not cover fall back to the built-in synth's GM bank. Call soundFontManifest({ uri }) in JS or sound_font_manifest(uri=...) in Python to see, per (channel, bank, program), whether each note resolves to 'sf2' or falls back to 'synth'; see the SoundFont guide for slot and manifest details.

Host your own instrument ​

Every runtime can host any instrument you write through the ExternalInstrument protocol: bounce({ instruments }) on Node and WASM, bounce(instruments=...) on Python. Events reach the instrument as UMP (Universal MIDI Packet) words, the MIDI 2.0 packet encoding, and the instrument adds its audio into scratch buffers the bounce hands it.

JavaScript (Node and WASM) ​

Only render is required; prepare, onEvent, latencySamples, and tailSamples are optional. The destination id is given beside the instrument, in the binding pair. onEvent receives { destinationId, words, renderFrame }. render(outputs, frames) gets one zero-filled Float32Array per channel (always two: the engine hosts an instrument as a stereo source whatever numChannels is); whatever the arrays hold when render returns is added into the bounce.

typescript
class SineInstrument {
  tailSamples = 4096;                       // release tail that extends an auto-length bounce
  voices = new Map<number, { phase: number; amp: number }>();
  sampleRate = 48000;

  prepare(sampleRate: number) {
    this.sampleRate = sampleRate;
    this.voices.clear();
  }

  onEvent({ words }: { words: number[] }) {
    const status = (words[0] >>> 20) & 0xf;      // 0x9 note-on, 0x8 note-off
    const note = (words[0] >>> 8) & 0xff;
    const velocity = words[0] & 0xff;
    if (status === 0x9 && velocity > 0) this.voices.set(note, { phase: 0, amp: (velocity / 127) * 0.3 });
    else if (status === 0x8 || status === 0x9) this.voices.delete(note);
  }

  render(outputs: Float32Array[], frames: number) {
    for (const [note, v] of this.voices) {
      const step = (2 * Math.PI * 440 * 2 ** ((note - 69) / 12)) / this.sampleRate;
      for (let i = 0; i < frames; i++) {
        const s = Math.sin(v.phase) * v.amp;
        for (const out of outputs) out[i] += s;
        v.phase += step;
      }
    }
  }
}

const { channels } = project.bounce({ numChannels: 2, instruments: [{ instrument: new SineInstrument() }] });
// Several instruments at once: instruments: [{ destinationId: 0, instrument: a }, { destinationId: 1, instrument: b }].

Every callback runs synchronously on the calling thread while the bounce is blocked, so a callback that returns a Promise is refused with a TypeError. A callback that throws stops all further callbacks and the bounce rethrows that first error once it returns (a native failure is reported ahead of it). Using the project from inside a callback (a mutation, a nested bounce, destroy) throws InvalidState. One instrument shared by tracks that feed different channel strips is refused, because callback audio carries no source-track attribution; bind one destination per strip.

Python ​

In Python, bounce(instruments=...) dispatches the same protocol. Only render is required; prepare, on_event, and the latency_samples / tail_samples attributes are optional (duck-typed). Events reach on_event as UMP words (see above), so a note-on arrives as a tuple of packet words rather than a decoded object.

python
import numpy as np
import libsonare as sonare


class SineInstrument:
    """A minimal external instrument: one sine voice per held note."""

    latency_samples = 0      # PDC (plugin delay compensation) you report to the compiler
    tail_samples = 4096      # release/effect tail for auto-length bounces; INT_MAX = unbounded

    def prepare(self, sample_rate: float, max_block_size: int) -> None:
        self.sample_rate = sample_rate

    def on_event(self, destination_id: int, ump_words: tuple[int, ...], render_frame: int) -> None:
        # Decode dispatched UMP words (note-on / note-off) and update your voices.
        ...

    def render(self, channels: np.ndarray, num_frames: int) -> None:
        # channels is a zero-filled (num_channels, num_frames) float32 array.
        # Sum your audio INTO it; never overwrite unrelated frames.
        channels += 0.0


with sonare.Project.from_json(project_json) as project:
    audio = project.bounce(
        instruments=[sonare.ProjectInstrumentBinding(instrument=SineInstrument())],
        num_channels=2,                        # total_frames omitted => length derived (+ tail_samples)
    )
    channels = audio.channels       # -> np.ndarray, shape (num_channels, frames)
    sample_rate = audio.sample_rate

Every callback runs synchronously on the thread that calls the bounce, so there is no cross-thread state to guard. An exception raised inside a callback propagates to the caller — your ValueError surfaces as a ValueError, not a silent dropout. tail_samples extends an auto-length bounce so a reverb or release tail is not clipped off.

To play several instruments at once, pass several ProjectInstrumentBinding records: each record binds one instrument to one MIDI destination.

Validate MIDI before bouncing ​

The compiler is forgiving: a MIDI clip with no instrument bound is a non-fatal warning, not an error. After compile() the result's diagnostics carry a warning entry (no error entry, so the project still compiles) with this message:

project contains MIDI clips; bounce is silent unless an instrument is bound

That message is your cue to bind an instrument in bounce. To catch a real problem, a stuck note, pre-flight each MIDI clip with validateMidiNotes, which checks that every note-on has a matching note-off:

validateMidiNotes returns { ok, unmatchedNoteOns, unmatchedNoteOffs } in WASM and Node and NotePairValidation(ok, unmatched_note_ons, unmatched_note_offs) in Python. A hanging note would sound until the render ends, so fix the events first; see validateMidiNotes for the call and Project MIDI for inspecting and repairing clip events.

Write the bounce to a WAV file ​

A Node or WASM bounce is planar: one Float32Array per channel. In the browser, interleave it into a 16-bit PCM WAV and offer it as a download:

typescript
function exportWav(channels: Float32Array[], sampleRate: number): Blob {
  const numChannels = channels.length;
  const frames = channels[0].length;
  const bytesPerSample = 2;
  const dataBytes = frames * numChannels * bytesPerSample;
  const buffer = new ArrayBuffer(44 + dataBytes);
  const view = new DataView(buffer);
  const writeStr = (offset: number, s: string) => {
    for (let i = 0; i < s.length; i++) view.setUint8(offset + i, s.charCodeAt(i));
  };

  writeStr(0, 'RIFF');
  view.setUint32(4, 36 + dataBytes, true);
  writeStr(8, 'WAVE');
  writeStr(12, 'fmt ');
  view.setUint32(16, 16, true);                                   // PCM chunk size
  view.setUint16(20, 1, true);                                    // PCM format
  view.setUint16(22, numChannels, true);
  view.setUint32(24, sampleRate, true);
  view.setUint32(28, sampleRate * numChannels * bytesPerSample, true);
  view.setUint16(32, numChannels * bytesPerSample, true);
  view.setUint16(34, 8 * bytesPerSample, true);
  writeStr(36, 'data');
  view.setUint32(40, dataBytes, true);

  let offset = 44;
  for (let i = 0; i < frames; i++) {
    for (const channel of channels) {                             // interleave while writing
      const s = Math.max(-1, Math.min(1, channel[i]));            // clamp before quantizing
      view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
      offset += bytesPerSample;
    }
  }
  return new Blob([buffer], { type: 'audio/wav' });
}

const { channels, sampleRate } = project.bounce({
  numChannels: 2,
  synthInstruments: [{ instrument: { preset: 'sawLead' } }],
});
const url = URL.createObjectURL(exportWav(channels, sampleRate));
// assign url to an <a download> and click it

What this writer does to the samples

The bounce is 32-bit float, and this writer reduces it to 16-bit integers in the simplest way:

  • Overs are clipped. A float bounce can go above 1.0 (0 dBFS); the Math.max / Math.min clamp cuts those peaks flat, which is audible distortion. Measure the peak first and lower the master if it exceeds 1.0.
  • Samples are truncated, not dithered. setInt16 drops the fraction, which leaves quantization error that follows the signal; on quiet fades and reverb tails it can be heard as grainy distortion. For a final 16-bit file, round instead of truncating and add TPDF dither (the sum of two independent random values of ±0.5 LSB each, where one LSB is a single 16-bit step) before rounding, or write 24-bit or 32-bit float WAV and let the delivery tool reduce it.

In Python, the CLI writes the WAV for you (next section); from the library, pass result.channels.T to soundfile for frames-first input, or transpose it in your own WAV writer.

Bounce from the CLI ​

The sonare CLI (both the Python package and the native build) has a project subcommand that loads a project JSON and renders it to WAV without writing any code:

bash
# Plain bounce (audio clips; MIDI tracks render silently)
sonare project bounce song.json -o master.wav --sample-rate 48000

# Route MIDI through the built-in synth, following the project's GM programs
sonare project bounce song.json -o master.wav --synth

# Or pin every destination to one preset from the NativeSynth catalog
# (`sonare project synth-presets` lists them all)
sonare project bounce song.json -o master.wav --synth saw
sonare project bounce song.json -o pad.wav --synth warmPad

# A project with unresolved audio sources needs their samples supplied first:
# open every source's own file:// URI in one pass...
sonare project bounce song.json -o master.wav --resolve-audio

# ...or bind one source explicitly by id (repeatable, once per source)
sonare project bounce song.json -o master.wav --audio 1=vocals.wav

# Inspect first: compile diagnostics (including the no-instrument warning)
sonare project compile song.json --json
FlagMeaning
project.jsonProject JSON (positional, required)
-o FILEOutput WAV
--sample-rate NMust equal the project rate (not a resample); defaults to the project rate
--frames NRender length in frames, at least 1; omitted renders through the last event and its tail
--channels N1, 2, 6, or 8, at most the scene master's width (default: the scene master's width)
--instrument-latency-samples NInstrument delay compensation in samples
--audio ID=WAVBind one decoded file to one audio source (repeatable)
--resolve-audioOpen the file:// URIs the project's sources carry
--synth [PRESET]Bare: follow the project's GM programs. With a value: pin every destination to that preset

A project's sources entries name their audio by URI only, and the library never opens one itself, so a project whose clips reference audio renders nothing until the command line supplies the samples. --resolve-audio opens the file:// URIs the document's sources already carry; any other scheme is refused by name rather than skipped:

Error: source 1 (https://example.com/take.wav): --resolve-audio opens file:// URIs only; pass --audio 1=FILE

--audio <source_id>=WAV instead binds one decoded file to one source, addressed by the numeric id from the project's sources array (or from the refusal message below); repeat the flag once per source. A source still unresolved when the render starts is refused with its id, its URI, and the option that would have supplied it:

Error: source 1 (file:///song/vocals.wav) has no audio; pass --audio 1=FILE or --resolve-audio

A bound source keeps the channel count of the file it was decoded from, so binding a mono take does not upmix it. midi-render accepts neither flag; a project bounced through it with an unresolved audio source still hits the bare Error: [7] Invalid state rather than a message naming options midi-render does not have.

Bare --synth follows the project's General MIDI program changes per channel, with channel 10 routed through the GM drum-kit map, and falls back to the sine patch for anything the map does not cover. Use it when the project carries real GM programs. --synth <preset> pins every destination to one preset from the NativeSynth preset catalog (--synth warmPad, --synth sawLead); sonare project synth-presets lists the names. SF2 and per-destination synth JSON remain binding-only (WASM/Node/Python); use the Project API for SoundFont-backed bounces. Other useful subcommands are project new, project validate, project synth-presets, and project abi.

Recipes ​

Catch a silent MIDI bounce before you ship it

Compile, read the warning, and only then choose an instrument.

typescript
const result = project.compile();
const hasMidiWarning = result.diagnostics.some((d) =>
  d.severity === 'warning' && d.message.includes('bounce is silent'),
);
const { channels } = hasMidiWarning
  ? project.bounce({ numChannels: 2, synthInstruments: [{ instrument: { preset: 'sawLead' } }] })
  : project.bounce({ numChannels: 2 });

With a clean bounce in hand you have a finished mix. To shape what each track sounds like before it reaches the master, tune its channel strip in the Mixing Engine; to capture more material to arrange and bounce, see Recording and Takes.