Skip to content

Compile, Save, and Load Projects ​

Project work has three boundaries. compile() checks whether the arrangement can become a renderable timeline. toJson() / fromJson() persist the arrangement model. Loading does not restore PCM, so decoded audio must be rebound before a bounce. Host-separated stems enter through an all-or-nothing import that creates ordinary audio tracks and clips.

TaskAPI
Check the arrangementproject.compile()
Persist the modelproject.toJson() and Project.fromJson(...)
Recover load warningsProject.fromJsonWithDiagnostics(...)
Rebind decoded audiounresolvedAudioSourceIds() and setSourceAudio(...)
Add host-separated stemsimportExternalStems(...)
Compile, persist, rebind, and render
Project editscompile()Deterministic JSONfromJson()Rebind PCMBounce
The saved model restores the arrangement; the host supplies decoded PCM again before rendering.

Compiling the arrangement ​

compile() turns the edited project into a renderable timeline and reports structured diagnostics. A diagnostic with severity 'error' means the timeline could not be built; one with severity 'warning' is non-fatal and the timeline is still renderable.

typescript
const result = project.compile();
// result.diagnostics -> [{ code, severity, targetId?, message }, …], empty when clean
//   code     -> a token such as 'danglingSourceRef' or 'midiClipNoInstrument'
//   severity -> 'error' | 'warning'
// result.timeline    -> present only with compile({ withTimeline: true }) and no error

for (const d of result.diagnostics) {
  if (d.severity === 'error') console.error(`${d.code} (target ${d.targetId}): ${d.message}`);
}

The project compiled when no diagnostic has severity 'error'.

A common non-fatal warning: a project with MIDI clips but no bound instrument compiles fine, but bounces silently. After a bounce you can read the warnings that render produced with lastBounceCompileResult():

typescript
project.bounce();
const last = project.lastBounceCompileResult();
// last.diagnostics[0] ->
//   { code: 'midiClipNoInstrument', severity: 'warning', targetId: 1,
//     message: 'project contains MIDI clips; bounce is silent unless an instrument is bound' }

lastBounceCompileResult() is undefined until the first successful bounce. Read a failed bounce’s error from the exception it throws. This method retains the last successful bounce’s result. In Python, project.compile() returns the same shape (diagnostics of code, severity, target_id, message, and timeline when called with with_timeline=True).

Save and load: deterministic JSON ​

toJson() serializes the whole project (tracks, clips, MIDI content, loop crossfades, tempo map, time signatures, markers, annotations, warp maps, automation, and part-rig selections) to deterministic JSON: the same project always produces byte-identical text. Project.fromJson(...) restores it. Loop crossfade fields are omitted when they are zero, so hard-loop projects keep a compact JSON shape. Keys are camelCase (sampleRate, activeTakeId, midiContent, tempoSegments, partRigs), and the document carries version: 7, the only schema this release reads.

Part rigs are stored under partRigs as entries keyed by destinationId and part. The part is 0–15, or 255 (PART_RIG_ALL_PARTS) for the destination default. Each entry has mode 'bank', 'none' or 'chain'; a chain carries 1–8 { processor, params } objects under inserts, with params a JSON object. 'bank' and 'none' take no inserts: leave inserts out, since an empty array is refused like any other inserts on a non-chain mode (RangeError). project.setPartRig({ destinationId, part, mode, inserts }) stores an entry even when no track currently routes to that destination, project.partRig({ destinationId, part }) reads it back (null when none is stored), and project.clearPartRig({ destinationId, part }) removes it. Project bounces apply entries to SoundFont and physical-model destinations; SMF export does not include them.

typescript
const json = project.toJson();
// … persist `json` to disk, a database, or postMessage …

const restored = Project.fromJson(json);
try {
  // restored.toJson() === json
} finally {
  restored.destroy();
}

Use Project.fromJsonWithDiagnostics(json) when you want to recover non-fatal load warnings (for example dangling source references preserved for repair):

typescript
const { project: loaded, diagnostics } = Project.fromJsonWithDiagnostics(json);
try {
  if (diagnostics) console.warn(diagnostics);
} finally {
  loaded.destroy();
}

Python mirrors this with project.to_json(), Project.from_json(json), and Project.from_json_with_diagnostics(json); release a project with close() (JavaScript: destroy(), or using).

A document that cannot load fails with InvalidFormat on every surface. The error message describes the cause. In JavaScript, a successful fromJsonWithDiagnostics call returns the names of recoverable diagnostics in its diagnostics string. WASM and Node throw SonareError; Python raises coded SonareError. The Python CLI exits 5 for a malformed project document, as the native CLI does.

DiagnosticCauseFatal
malformed_jsonThe text is not valid JSONYes
not_an_objectThe document is valid JSON but not an objectYes
missing_versionversion is absent (the message says it must be given) or not a numberYes
invalid_versionversion is negative or fractionalYes
unsupported_schema_versionversion is a whole number other than 7, older or newerYes
invalid_sample_ratesampleRate is not a whole number of hertz in 8000 to 384000Yes
invalid_formatAn unknown key anywhere in the document, including a scene (unknown key <path> (expected <sorted accepted keys>)), or a container or array element of the wrong type (tracks must be an array, clips[0] must be an object)Yes
invalid_clip_take_structureA clip's takes repeat an id or use id 0, activeTakeId names no take, a take sits on a MIDI track, or comp segments overlap, run past the clip end or carry a negative crossfadeYes
dangling_clip_sourceA clip names a source id the document does not define; the clip is kept so it can be repairedNo, returned in diagnostics

Keys starting with $ or x- are accepted and ignored in project and scene record fields; processor params keys must still be recognized. A dangling reference loads with the warning dangling_clip_source: clip 1 references missing source 99, and compile() then reports it as an error (danglingSourceRef) until the clip is repaired. See Mixing Scene JSON for the same unknown-key rule on a standalone scene.

An unread insert parameter is fatal. A typed setMixerScene(scene) refusal names scene.strips[i].inserts[j].params.<key> or scene.buses[i].inserts[j].params.<key> and lists that processor's accepted keys in sorted order. Loading the same scene from project JSON raises InvalidFormat with the indexed stored-scene path. These messages do not suggest a replacement spelling. Project JSON also preserves a separate hint for known earlier built-in assist-module IDs; it does not apply to scene or ordinary unknown keys.

Reading the model back, and rebinding audio after a load ​

Project JSON stores the arrangement, not the PCM. A loaded project therefore knows it has a source, but has no samples behind it. Three read-only descriptor lists plus the PCM and source-metadata setters close that loop.

What the JSON holds
audio tracktake 1take 2take 3comp laneMIDI trackautomation lanebar 1bar 2bar 3bar 40481216position in PPQ · 1.0 = one quarter noteclip startPpq 0 · lengthPpq 8active take — fills uncovered regionstake 1take 3take 2segments pick a take; nothing is copiedMIDI clip
  • take 1
  • take 2
  • take 3
The JSON holds this arrangement: tracks, clips, takes and automation. The audio under each audio clip is not in it; the host decodes it and binds it back.
typescript
const loaded = Project.fromJson(json);

for (const track of loaded.tracks()) {     // { id, kind, midiDestinationId, gain, pan, mute, solo, name }
  console.log(track.id, track.name);
}
for (const clip of loaded.clips()) {       // { id, trackId, sourceId, sourceKind, startPpq, lengthPpq, … }, in quarter notes
  console.log(clip.id, clip.startPpq, clip.lengthPpq);
}
for (const source of loaded.unresolvedAudioSources()) {
  // { id, kind, numChannels, storageHandleId, sampleRateHint, nameOrUri, contentHash?, externalStemRole? }
  const { channels, sampleRate } = await decodeFromYourStorage(source.nameOrUri);
  loaded.setSourceAudio({ sourceId: source.id, channels, sampleRate });
  loaded.setAudioSourceMetadata({ sourceId: source.id, contentHash: 'sha256:...', externalStemRole: 'lead-vocal' });
}

const audio = loaded.bounce();
python
loaded = sonare.Project.from_json(json_text)

for track in loaded.tracks():
    print(track.id, track.name)
for clip in loaded.clips():
    print(clip.id, clip.start_ppq, clip.length_ppq)

unresolved = set(loaded.unresolved_audio_source_ids())
for source in loaded.sources():
    if source.kind != "audio" or source.id not in unresolved:  # skip MIDI
        continue
    channels, sample_rate = decode_channels_from_your_storage(source.name_or_uri)
    loaded.set_source_audio(source.id, channels, sample_rate)
    loaded.set_audio_source_metadata(source.id, "sha256:...", "lead-vocal")

audio = loaded.bounce()

From the command line, sonare project bounce --resolve-audio opens the file:// URIs the sources carry (see Bounce from the CLI).

tracks(), clips() and sources() return every entry in the stored order (Python tracks(), clips(), sources() likewise). They are descriptors, not handles: mutating a returned object changes nothing. Use them to render a project the host loaded from disk, or to build a UI over a project your own code did not construct.

setSourceAudio({ sourceId, channels, sampleRate }) rebinds decoded planar PCM (one Float32Array per channel) to a source before a bounce, the step that turns "loaded arrangement" into "renderable project". Python calls set_source_audio(source_id, channels, sample_rate) with equal-length channel planes or a channels-first array. Pass the decoded PCM's actual rate, not sample_rate_hint.

startPpq and lengthPpq are positions and lengths in quarter notes (1.0 is one quarter note), not MIDI ticks; see Ticks and PPQ and Clips and Tracks.

The sampleRate you pass is the real rate of the PCM, so give the decoded rate; the stored sampleRateHint is only a hint and is 0 when unknown. If it differs from the project's sample rate, the compile step resamples the source to the project rate (a 441 Hz tone bound at 44100 Hz bounces at 441 Hz in a 48000 Hz project). A bounce is never resampled: bounce() returns audio at the project rate and has no rate option in JavaScript. Stem import below does no resampling either.

unresolvedAudioSources() returns the descriptors of the sources that still need decoded PCM after deserialization, in the order of unresolvedAudioSourceIds(), so a loader can read each nameOrUri without a second lookup; the URI is returned untruncated. A source gets its nameOrUri from the sourceUri of the metadata-only addClip({ trackId, startPpq, lengthPpq, sourceUri }) that created it (an audio clip added with channels is already resolved). storageHandleId is the id of the handle that holds the PCM, 0 while the source is unresolved. A source kind is 'audio' or 'midi': MIDI sources have no PCM to bind and no source metadata to update, so a walk over sources() skips them. contentHash and externalStemRole are metadata on audio-source descriptors and are absent when unset. setAudioSourceMetadata({ sourceId, contentHash, externalStemRole }) replaces both strings as one undoable edit; omit a field to clear it (an empty string is refused with RangeError). Python uses set_audio_source_metadata(source_id, content_hash, external_stem_role) with None to clear, and the descriptor fields content_hash / external_stem_role; the C ABI is sonare_project_set_audio_source_metadata, whose getter returns heap strings that the matching free function must release. Node takes the same { sourceId, … } request object as WASM.

Importing host-separated stems ​

If your app already ran source separation (or simply has per-instrument WAVs), importExternalStems turns them into one audio track and clip each, in one transaction.

typescript
const { trackIds, clipIds } = project.importExternalStems({
  sampleRate: 48000,
  stems: [
    { name: 'vocals', layout: 'stereo', channels: [vocalL, vocalR], startFrame: 0 },
    { name: 'drums',  layout: 'stereo', channels: [drumL, drumR],   startFrame: 0 },
    { name: 'bass',   layout: 'mono',   channels: [bassMono],       startFrame: 0, role: 'bass' },
  ],
});

The import is all-or-nothing: if any stem is rejected, the project is left untouched rather than half-populated. It performs no resampling, no retiming, and no gain compensation — every stem must already be at sampleRate, which must equal the project's sample rate (a different one is a RangeError), and startFrame places it on the project timeline as-is. The optional per-stem role is host metadata that round-trips through the serializer and does not change any DSP.

Continue to rendering ​

After the project has a timeline and every required audio source is bound, continue with Bouncing Projects. This page does not duplicate instrument-binding or render-option details.