Build a DAW UI
This guide builds the core loop of a DAW user interface on the Studio API v1: open a project, draw its waveforms, edit clips, play it, mix it, automate it and export it. Every step names the operations to call; the reference has their full schemas. It assumes you have a user access token with projects:list projects:read projects:write daw:read daw:write audio:listen media:upload exports:read (see Getting started).
The examples use a small helper. It sends the token, adds an Idempotency-Key to every mutation and turns the error envelope into an exception:
const BASE = "https://freestyle.audio/api/v1";
async function api(method, path, body, headers = {}) {
const res = await fetch(BASE + path, {
method,
headers: {
Authorization: `Bearer ${token}`,
...(body !== undefined ? {"Content-Type": "application/json"} : {}),
...(method !== "GET" ? {"Idempotency-Key": crypto.randomUUID()} : {}),
...headers,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (res.status === 304) return {notModified: true};
const data = await res.json();
if (!res.ok) throw Object.assign(new Error(data.error.message), data.error, {status: res.status});
return Object.assign(data, {etag: res.headers.get("ETag")});
}When you retry a failed request, reuse its Idempotency-Key instead of generating a new one, so a request that did reach the server is not applied twice.
1. Open a project
GET /projectslists the projects the user owns or that are shared with them, each with the user'srole,shared(shared with you: you are not the owner), the project'svisibilityandliveRoom. Page withlimitandcursor(the previous page'spagination.nextCursor). Create one withPOST /projects.GET /projects/{project_id}returns everything a timeline needs in one read:lanes,clips,bpm,timingMap,masterGain, the user'sroleand thetimelineRevision, which is also theETag. Keep the ETag: it is theIf-Matchfor timeline edits.- Disable editing controls when
roleisviewer; the server would answer403 editor_requiredanyway. - Open an interactive session so edits by other people, the Studio and assistants arrive as patches, and start live monitoring so the user hears the engine.
const project = await api("GET", `/projects/${projectId}`);
let timelineEtag = project.etag; // = project.timelineRevisionLarge timelines: GET /projects/{project_id}/lanes and GET /projects/{project_id}/clips (filter with lane_id) page the same data. Send the last ETag as If-None-Match to poll for changes for the price of a 304.
2. Draw waveforms
GET /projects/{project_id}/clips/{clip_id}/waveform returns per-channel min / max / rms buckets over a range of the clip's source frames (raw PCM in [-1, 1], before clip gain and effects), with sample_rate, channel_count, frame_count and a revision (also the ETag).
Frames index the whole source file, so one set of peaks serves every clip cut from it and every zoom level. Waveforms is the full recipe the Studio's own timeline follows, with a JavaScript example. In short:
- Read each source once, in tiles of up to 8192
buckets, and keep the peaks on the client as a pyramid of levels. Do not request per zoom level or per pixel width: zooming and scrolling should only choose which stored level and slice to draw. - Key what you keep by
revision. It changes only when the source audio changes (for example after a sample edit), and clips cut from the same source report the same one. Revalidate withIf-None-Match. - Use
clip_id=backingfor the backing track. The clip must be loaded in the live session; a clip that is not answers404 waveform_unavailableor409 target_not_loaded. Load a stored clip withPOST …/clips/{clip_id}:attachToSession. - Place a clip on the timeline with its
startMs,audioOffsetSec(where in the source the clip starts) anddurationSec;sourceDurationSecis the length of the whole source file, the bound for slipping or un-trimming (audioOffsetSec + durationSec <= sourceDurationSec).
3. Edit clips
Move, trim, duplicate and delete: clips:batch
POST /projects/{project_id}/clips:batch applies up to 256 ops in one transaction, mirrored in the live engine. A gesture that touches several clips (dragging a selection, a ripple) is one batch, so it either applies completely or not at all.
| op | Does | Fields |
|---|---|---|
update | Move or trim an existing clip. | id plus any of start_ms, duration_sec, audio_offset_sec; omitted timing is kept. |
insert | A new clip that plays an existing clip's source (duplicate, split half). | A new id, source_id, start_ms, duration_sec, audio_offset_sec. |
remove | Delete a clip (it can be restored). | id. |
restore | Bring a removed clip back. | id, start_ms, duration_sec, audio_offset_sec. |
// Trim the start of a clip by 250 ms, guarded twice:
// If-Match = the timeline you drew, expected = the clip as you saw it.
const res = await api("POST", `/projects/${projectId}/clips:batch`, {
ops: [{op: "update", id: clip.id,
start_ms: clip.startMs + 250,
audio_offset_sec: clip.audioOffsetSec + 0.25,
duration_sec: clip.durationSec - 0.25,
expected: {start_ms: clip.startMs, audio_offset_sec: clip.audioOffsetSec}}],
}, {"If-Match": timelineEtag});
timelineEtag = res.etag; // the new timeline revision- Always send
audio_offset_secback unchanged when you do not mean to change it; never send a guessed0. 412 timeline_revision_conflict: the timeline changed since you read it. Reload (or apply the patches from your interactive session) and redo the gesture.412 conflict: one op'sexpectedno longer matches.400 invalid_opnames the failing op indetails.opIndex; nothing was applied.
Move a clip to another lane: :move-to-lane
clips:batch never changes a clip's lane. For a cross-track paste or a vertical drag, call POST …/clips/{clip_id}:move-to-lane with lane_id and an optional start_ms.
- The destination must be an audio lane of the same project. A backing, pattern or instrument lane is refused with
400 lane_not_audio, and another project's lane is404. - Guard it with
If-Match(the timeline revision; a stale one is 412) and/orexpected: {lane_id, start_ms}, which answers409 clip_changedif the clip moved meanwhile. - The response has the updated clip card, the new timeline ETag and
undo: {op: "move", clip_id, lane_id, start_ms}. Posting thatlane_idandstart_msback to the same endpoint undoes the move. engine_reload_required: truemeans the move is saved, but the live session must reload before it plays.
Clip gain and clip mute
PUT …/clips/{clip_id}/gainsets one clip's level (gainlinear 0..4, 1 = unity), before the lane's plug-ins and fader. It is saved (the clip card'svolume, restored when the session reloads), moves the timeline revision, and is applied to a running session at once. The response hasundo: {op: "gain", clip_id, gain}: PUT that gain back to undo.PUT …/clips/{clip_id}/mutesilences one clip while the rest of its lane plays, with the sameundoandengine_appliedfields.- Both take
If-Match(the timeline revision).engine_reload_required: truemeans the value is saved but no running session took it yet.
Split, delete and trim a time range
POST /projects/{project_id}/time-range-edits does Audacity-style range edits across lanes as one atomic engine batch: operation = split, delete (with ripple to close the gap) or trim_to_selection, over start_ms/end_ms or start_frame/end_frame (+ sample_rate), optionally limited to lane_ids.
- Send
dry_run: truefirst to preview the plan (clips_after,cuts,skipped_lanes) for a confirmation UI. - The response has
undo.inverse_ops. Keep it on your undo stack: posting it toclips:batchundoes the edit. - The
Idempotency-Keyalso seeds the ids of new clips, so a retry creates the same clips, not duplicates.
Sample-level and region edits
- Pencil.
POST …/clips/{clip_id}/sample-editsoverwrites source samples (up to 64 ranges, 1 s of frames per call) withIf-Match= the waveform revision you drew on, and a requiredIdempotency-Key.…/sample-edits:undosteps back (8 steps kept). - Region effects.
GET /region-effectsis the catalog.…/region-effects:previewrenders a selection without changing the project;…/region-effects:applyreplaces exactly the selection with a new processed asset and returns a job (poll it). Both count as Mozart AI usage. Withmode: "in_place"the job isdoneonly once the live engine plays the new source version (engine_status: "swapped", or"replay"for a repeated key), soget_clip_waveformreports the returnedrevisionandsample-edits:undotakes it as If-Match. If the engine cannot load the version the job fails withengine_swap_failed,engine_statusset to the engine's code (source_unavailable,revision_conflict,clip_not_loaded,session_project_mismatch,source_not_in_project,sample_rate_mismatch,swap_failed,live_revision_mismatch,engine_timeout,engine_session_contended,engine_session_not_found,engine_restarting,engine_update_requiredorengine_error) and nothing committed (rolled_back: true): the clip keeps its previous audio and revision, and retrying with the same idempotency key is safe.
Stem splitter
POST …/clips/{clip_id}/stems{"mode": "vocals" | "four_stems" | "instruments" | "drums", "replace": true}splits one clip (clip_id=backingfor the backing slot) on the GPU, like the Studio's Extract stems. Send anIdempotency-Key. It answers202withjobId,expectedStemsand aLocationheader.drumson audio that is not already a drum stem runs asdrums_full(vocals, bass, other plus the kit pieces).- Poll
GET …/stems/jobs/{job_id}every ~10 s (Retry-After). It is a pure read.donelists every created lane (laneId,stem,name,clipIds), aligned to the source clip, andsourceMuted: withreplace=truethe source is muted so the mix sounds the same; withfalsethe stem lanes land muted. An open Studio loads the new lanes itself; a session you drive headless plays them afterengine:reload. - One undo:
POST …/stems/jobs/{job_id}:undoremoves exactly the lanes and clips the job created and un-mutes the source it muted (a live session drops them at once). It is idempotent; the job then readsundone. - One split runs per project at a time (
409). Splits are metered like the Studio's (see limits). No audio passes through the API: the separator fetches the source and stores the stems itself.
Lanes and media
- Lanes: create, rename or recolor, reorder, duplicate, delete and restore.
- Duplicating a lane copies an audio lane (vocal, audio or guitar) with its clips, effect chain, plug-in states and mix into a new lane directly below it, and loads the copy into a running session. The response's
undois thedeleteLanecall that removes the copy and leaves every other lane exactly where it was. An instrument lane copies its generator with its saved patch state and its effect chain (new plug-in instance ids), and its notes come along as independent pattern copies on a pattern row of their own; a pattern row copies its patterns as independent copies placed at the same positions, so editing the copy never edits the source. Only the backing lane is refused (409 lane_kind_not_duplicable). - Deleting an instrument lane also removes, in the same request, every pattern channel that played it (with its notes and CC automation), so those patterns stay editable.
deletedPatternChannelslists them as{patternId, channelId}, andrestoreLaneputs them back at their rack positions with their notes (restoredPatternChannels). To change the instrument and keep the lane, usereplaceLaneInstrumentinstead. - Audio:
POST /media/upload(base64, up to 25 MB,Idempotency-Keyrequired) orPOST …/audio:fromUrlfor larger files. Upload quotas apply (see limits).
4. Transport
| Control | Operation |
|---|---|
| Play / pause | POST …/transport/play, POST …/transport/pause |
| Seek, or seek and play | POST …/transport/seek with seconds (or tick, 96 PPQ) and optional play: true |
| Play a selection once | POST …/transport/play-range: the engine stops exactly at the end, sample-accurate |
| Count-in, then play | POST …/transport/play with count_in_beats (and seek_seconds): clicks, then the transport starts on the beat, with no recording armed (details) |
| Loop | PUT …/transport/loop with enabled and a range in seconds or ticks. The switch keeps the region: {"enabled": false} keeps it, {"enabled": true} alone loops it again, and enabling with no region is 409 loop_region_required |
| State | GET …/transport; the playhead from GET …/transport/clock or the socket's clock frames |
Scrubbing is a seek while playing: the engine keeps rolling at the new position. Draw the playhead at the position the user hears, which lags the engine clock; see Drawing a playhead.
5. Mixer, buses and plugins
- Lane strip: gain (linear, 1 = unity), pan (-1..1), mute, solo; the beat is lane
backing. Master gain is 0..4. - While a fader or knob is moving, send
persist: false(where the operation has it) or use the interactive session's gesture frames, then one final call that saves. That keeps you well inside the rate budget. - Buses: list, create, gain, mute, solo, and lane routing.
- Aux sends: a lane keeps its one output route and can also send a copy to any number of other buses with
PUT …/lanes/{lane_id}/sends/{bus_id}(levellinear 0..2, 1 = unity;pre_fadertaps before the lane fader and pan, and mute/solo still silence it), remove and list them. Sends sum into the bus before its plugins, fader and delay compensation, live and in exports. They are saved with the project and travel with duplicateProject, duplicateLane, restoreLane and project saves. Every reply carriesundo, and Mozart AI's undo reverts a send change. Limits: the beat (backing) has no lane row and cannot send (400); sends target buses other than master; bus-to-bus sends are not supported (buses sum to master only); at most 16 sends per lane. - Plugins: list a lane's chain, read parameters, set a parameter, bypass, apply a preset; the same for bus chains.
Live engine state, MIDI and recording
GET …/engine/statereturns tracks, live clips, buses, the mix, transport and history status in one read. Use…/engine/tracksand…/engine/mixfor lighter polling.- Audition a keyboard with
POST …/engine/midi(pair everynote_onwith anote_off), and call…/engine/midi:allNotesOffon blur. - Record a take: open your microphone uplink with
…/live-ingest/offer(WebRTC; the audio goes from your client straight to the engine, never through this API), arm with…/recording:start, sendtake_startand latertake_stopwith your owntake_idon the uplink's data channel, then…/recording:finalizewithconfirm=trueand thetake_id: the take is scanned and lands as a clip.GET …/recordingreports the record state. - Count-in: send
count_in_beats(1-8) to…/recording:start. The engine clicks the metronome that many beats and answers at the recording boundary withresponse.count_in(beat_samples,bpm,first_click_sample,recording_start_sample, …). Addseek_secondsandstart_transport: trueto pre-roll a stopped transport so the downbeat lands on the boundary. Finalize ends the arm. - Anything else the engine can do is in the engine action catalog, and each action has a typed
engine_<action>operation (see Engine actions).
6. Automation and timing
Automation envelopes
- Read:
GET …/automationfor the project, or per lane, clip or plugin. - Create on a clip:
POST …/clips/{clip_id}/automationwith atarget({"kind": "clip_gain"}or a plugin parameter on the clip's lane) andpoints(timeSecfrom the clip start,value0..1,curvelinear|bezier|hold|db). - Edit: replace an envelope, or add, move and delete points.
Tempo and meter
GET …/timing-map: tempo segments (ticks at 96 PPQ, constant or linear ramps), the meter map and pattern meters, with a revision as the ETag.PUT …/timing-mapreplaces tempo and/or meter atomically withIf-Match= the revision you read;…/timing-map:undoreverts. A simple BPM box can usePUT …/tempo. By default (mode: "keep_time") a tempo change never time-stretches audio: clips stay at their absolute times.mode: "stretch_audio"is Logic's "Adapt Project Tempo": audio clips are time-stretched with pitch kept and every clip and pattern start scales by old/new BPM, so content stays on its bar. It runs as a job (202 +Location; pollGET …/tempo-jobs/{job_id}), andPOST …/tempo-jobs/{job_id}:undorestores the tempo, positions and original audio exactly. Hidden loop repeats tile their clip's measured rendered length, automation envelopes are rescaled with the audio, and when the backing is stretched its bar-ruler anchor (backing.firstBeatSec) moves with it. If the open live engine cannot be reloaded after the save, the job issucceededwithengine_reload_required: true: callPOST …/engine:reload.- Key:
PATCH /projects/{project_id}withkey(C … B, sharps) andscale(major,minor,chromatic);key: nullgoes back to Auto.POST …/key-analysisdetects a key from a take without changing the project. - Draw the bar ruler with
POST …/timing-map:convert(up to 256 positions between ticks, bar:beat:tick, seconds and frames), so your grid matches the engine exactly.
Patterns (step and piano-roll) and their placements have their own group: Patterns.
Sample channel waveforms
GET …/pattern-samples/{audio_file_id}/waveform returns normalized peaks for a Channel Rack sample. Samples ingested before peaks were stored are decoded once by the project's live engine (which holds the media decrypt grant) and the peaks are saved, so that first read can take a few seconds and answers source: "computed"; later reads are source: "stored". 404 waveform_unavailable (with details.reason) only when the engine cannot decode the sample either.
Sequencing a sample channel
Steps and notes on a sample channel are pattern events with type: "sample" (PatternNote): the channel's sample plays at its natural pitch, or repitched by note against the root pitch (or by an explicit playbackRate), scaled by velocity. midi / note events are for instrument channels; they do not trigger a sample channel.
Delete and undo a pattern placement
A Playlist Delete followed by Undo must bring back the same placement, not a copy. Recreating it with createPatternPlacement mints a new id and loses its loop phase, per-source bus overrides, row EQ and gain, and its automation.
DELETE …/pattern-placements/{placement_id}answersundo: {op: "restore", placementId, before, restoreToken, timelineRevision}.beforeis the stored placement: every persisted field (patternId,laneId,startMs,durationMs,loopDurationMs,repeatCount,offsetMs,windowMs,loopPhaseMs,busId,sourceBusOverrides,displayOrder,muted,soloed,nativeEq,rowGain,name) plus the clipautomationenvelopes attached to it.restoreTokenis signed and bound to this deletion and your account, and it expires after 24 hours.timelineRevisionis the revision right after the delete. Keep the whole object on your undo stack.- To undo, call
POST …/pattern-placements/{placement_id}:restorewith{"before": undo.before, "restoreToken": undo.restoreToken}andIf-Matchset toundo.timelineRevision. That soft-deleted row comes back with its original id and its automation, the engine re-schedules patterns, and open Studios refresh. - Only a placement you deleted, and only that deletion, can be restored. A forged, expired or other-placement token is
403 restore_token_invalidorrestore_token_expired. If the placement changed or was deleted again since, the answer is409 restore_token_stale; undo the later delete with its own token. Placements removed by the system (a split undo, a version restore) have no token and cannot be restored this way. - The stored row always wins. If it no longer matches
before, the answer is409 placement_snapshot_mismatchwithdetails.mismatchedFields. A live placement is409 placement_not_deleted. If its pattern or lane was deleted since, the answer is409 pattern_deletedorlane_deleted; restore that first. - A stale
If-Matchis412 timeline_revision_conflict. Send anIdempotency-Key: a retry of an applied restore replays the same response.
7. Undo and history
- The Studio's undo log:
GET …/history,…/history:undoand…/history:redo. It only holds edits the Studio recorded, and undo/redo just move its cursor and return the entry for you to apply. Your API edits are not in it: undo them with the undo objects they return (above). - Keep your own undo stack for direct edits: range edits return
undo.inverse_ops, timing-map writes return the inverse call, sample edits have their own undo, stem splits have…/stems/jobs/{job_id}:undo, and pattern-placement deletes returnundo.beforeandundo.restoreTokenfor:restore. POST …/ai:undoreverts the latest Mozart AI or Pro action, as the Studio's undo does.- Version history: save, list saves and restore (needs
confirm=true).
8. Listen and export
- Optional check:
POST …/listenrenders and measures a short excerpt (levels, clipping, timing and key fit). POST …/exportswith anIdempotency-Keystarts a full-mix render and answers202with ajobId. A retry with the same key never starts a second export.- Poll
GET …/exports/jobs/{job_id}every few seconds (honourretryAfterSec). When it is complete it has a one-hour signeddownloadUrl. GET …/exportslists earlier exports with fresh download links.
const job = await api("POST", `/projects/${projectId}/exports`, {});
let status;
do {
await new Promise((r) => setTimeout(r, 3000));
status = await api("GET", `/projects/${projectId}/exports/jobs/${job.jobId}`);
} while (["queued", "rendering", "uploading"].includes(status.status));
// complete: download status.downloadUrl; failed / fallback_required: the render did not finishAdding an assistant to your DAW
To let users type instructions ("make the vocal brighter", "loop the chorus"), call POST …/ai/commands. It runs the same planner as the Studio's assistant bar and counts as Mozart AI usage. To let an external assistant (ChatGPT, Claude) work on the same project, connect it to the MCP server; its edits reach your interface through the interactive session like anyone else's.