Comp One Performance from Several Takes
Comping is how several attempts at one part become one performance: you keep every take, then choose which take plays over each stretch of the timeline. This page is the project-side half of recording. Recording and Loop Takes gets the audio in (capture, the browser microphone, loop passes split into takes); this page is what you do with the takes afterwards — comp segments and seam crossfades on a clip, and, for takes recorded as separate passes rather than on a loop, shared cut points and alignment.
Take and comp
A take is one recorded attempt. A comp is the edited keeper assembled from parts of several takes. The original takes stay in the clip; comp segments only choose which take plays over each PPQ range. See Takes and comping for the concepts.
What You Will Learn
- set a clip's takes and its active take, and comp across them with
setClipTakes/setClipCompSegments; - soften a splice with
crossfadePpqand know what the edit compiler renders; - find the cut points several free takes share with
splitSilenceCommonWithReport, slice every channel on the same frames withremixAlignedIntervals, and warp a take that drifts under its reference withalignTakeToReference.
Takes and comp segments
clipId below is a clip that carries takes: the one addLoopRecordingTakes returns, or any audio clip you give takes. A clip can carry an ordered list of takes plus an active take id (the take that plays when no comp says otherwise) and a list of comp segments (PPQ ranges, each pointing at the take to play there). Both are undoable edits and both round-trip through JSON.
// takes: each has a stable id; sourceOffsetPpq slides a take's source under the clip.
project.setClipTakes(clipId, [
{ id: 1, name: 'take A' }, // no sourceId: plays the clip's own source
{ id: 2, sourceId: takeBSourceId, name: 'take B' }, // a different recording; without it both takes play the same audio
], { activeTakeId: 2 });
// comp segments: each PPQ range picks one take. Verses from A, chorus from B.
project.setClipCompSegments(clipId, [
{ startPpq: 0, endPpq: 2, takeId: 1 },
{ startPpq: 2, endPpq: 4, takeId: 2 },
]);# takes: each has a stable id; source_offset_ppq slides a take's source under the clip.
project.set_clip_takes(clip_id, [
{"id": 1, "name": "take A"}, # no source_id: plays the clip's own source
{"id": 2, "source_id": take_b_source_id, "name": "take B"}, # a different recording
], 2) # active_take_id
# comp segments: each PPQ range picks one take. Verses from A, chorus from B.
project.set_clip_comp_segments(clip_id, [
{"start_ppq": 0.0, "end_ppq": 2.0, "take_id": 1},
{"start_ppq": 2.0, "end_ppq": 4.0, "take_id": 2},
])Each ProjectClipTake is { id, sourceId?, sourceOffsetPpq?, name? }; each ProjectClipCompSegment is { startPpq, endPpq, takeId?, crossfadePpq? }. Take ids must be unique and non-zero, and any takeId referenced by a comp segment must match an existing take — a bad reference throws a RangeError, so the edit fails loudly rather than corrupting the clip. Segments must also be in order, must not overlap, must stay inside the clip, and each must have a positive length. An omitted takeId is the deliberate exception: it falls back to the clip's active/base take for that region, so you can leave a segment on the active take without naming an id; an explicit 0 is refused.
Softening the seam
Two takes are two different signals, so a comp splice steps the waveform wherever they disagree. crossfadePpq fades a segment in over the part before it, so the switch completes exactly where the segment starts and the clip length does not move. The fade is equal-power: the squared gains of the two takes sum to one. That holds the level steady when the two signals are unrelated, which is the usual case for two separate takes. Across a seam between near-identical material (the same take, or a doubled part played very tightly) the level rises by up to about 3 dB at the middle of the fade instead; Fade curves and crossfades explains why.
project.setClipCompSegments(clipId, [
{ startPpq: 0, endPpq: 2, takeId: 1 },
{ startPpq: 2, endPpq: 4, takeId: 2, crossfadePpq: 0.25 }, // blend in over a quarter note
]);0, the default, is the butt join: segments meet with no overlap. A crossfade must fit inside both its own segment and the stretch of the previous part ahead of it, and the first segment has nothing ahead of it, so it takes 0 only. A value beyond those limits makes setClipCompSegments throw a RangeError; it is not clamped.
The activeTakeId option is optional. Omit it and the clip keeps playing its base source with no active-take override — useful when you have defined takes but do not want any of them to replace the original clip audio by default. A given activeTakeId must match the id of one of the takes you pass; an explicit 0 is refused.
Comping also composes safely with the other clip edits: splitClip and trims carry the takes, their sourceOffsetPpq values, and the covering comp segments over to the resulting clips, so cutting a comped clip does not lose the comp. The one combination that is refused is loop mode with comp segments that split the clip — a looped clip repeats one continuous region, so an edit that would create both is rejected instead of producing a comp that cannot loop.
Active take vs comp segments
The active take is the single take that plays when there are no comp segments — handy while you are still auditioning. Comp segments override that per region: wherever a segment covers a position, its takeId wins; outside every segment the active take fills in. Build the comp by adding segments over the active take, not by replacing it.
How the edit compiler renders a comp
When you compile() (or render) a project, the edit compiler walks the clip's timeline and, for each position, resolves which take's audio to read: a covering comp segment's take if one exists, otherwise the active take. Each take's source is read at its own sourceOffsetPpq, so a take that was recorded slightly late can be nudged into place without re-recording. The compiled timeline therefore plays one seamless performance assembled from many takes — the comp is a view, and the original takes stay intact for re-comping later.
JSON round-trip
project.toJson() serializes takes, the active take, and comp segments ("takes", "activeTakeId", "compSegments"); Project.fromJson(json) restores them. Because comping is non-destructive metadata over the takes, saving and reloading a project preserves every alternate take and your comp — you can keep refining the comp across sessions.
Comp two takes and save
project.setClipTakes(clipId, [
{ id: 1, name: 'take A' },
{ id: 2, name: 'take B' },
], { activeTakeId: 1 });
project.setClipCompSegments(clipId, [
{ startPpq: 0, endPpq: 2, takeId: 1 }, // first half from take A
{ startPpq: 2, endPpq: 4, takeId: 2 }, // second half from take B
]);
const json = project.toJson(); // contains "takes" + "compSegments"
const restored = Project.fromJson(json); // comp survives the round-trip
restored.destroy();Comping free takes: shared cut points and alignment
Loop takes arrive on the grid: every pass covers the same PPQ range, so addLoopRecordingTakes splits them by length alone. Takes recorded as separate passes, each a fresh run through the part against a guide vocal or a backing track, do not. A take sung live drifts against its reference, a little ahead here and a little behind there, so no single offset places it, and comping needs every take cut at the same places. Signatures are on the JavaScript API page; this section gives the order the calls go in and how to read what they return.
| Situation | Call | Result |
|---|---|---|
| Takes line up (loop passes, takes tracked to a click) | splitSilenceCommonWithReport, then remixAlignedIntervals | Shared cut points, the same frames on every channel |
| One take drifts against the reference | alignTakeToReference, then setWarpMap | Warp anchors; the comp is cut on the project timeline |
| Unsure which applies | Read report.silenceCeilingDb against topDb | The table under Cut points the takes share |
Cut points the takes share
What takes of one part share is their silence, not their sound: a take that happens to go quiet where another is still singing must not be cut there. splitSilenceCommon({ signals }) takes all the takes at once and returns the union of each take's sounding intervals, in the same flat [start0, end0, start1, end1, …] Int32Array that splitSilence returns for one signal, merged where they touch, so every gap between the returned intervals is silent in all takes at once and a cut placed in a gap lands mid-phrase in none of them. Takes of unequal length need no padding: a shorter take contributes nothing past its own end, which is the same as being silent there. A single signal answers exactly as splitSilence does. Cutting is left to you, and it is an array slice.
splitSilenceCommonWithReport returns the identical intervals plus a report. The report exists because one interval covering everything is the answer to three different situations, and the interval list cannot separate them:
import { splitSilenceCommonWithReport } from '@libraz/libsonare';
const topDb = 60; // the default: a frame is silent when it sits this far under its own take's peak
const { intervals, report } = splitSilenceCommonWithReport({
signals: [takeA, takeB, takeC], // one Float32Array per take, one channel each
topDb,
});
// intervals -> Int32Array [start0, end0, start1, end1, ...], valid for every take
// report -> { silenceCeilingDb, maxSignalIntervals, minSignalIntervals }import libsonare as sonare
top_db = 60 # the default
result = sonare.split_silence_common_with_report([take_a, take_b, take_c], top_db=top_db)
intervals = result.intervals # (n, 2) integer array of [start, end) frames, valid for every take
report = result.report # silence_ceiling_db, max_signal_intervals, min_signal_intervalsRead silenceCeilingDb, the largest topDb at which every take still shows silence, against the topDb you passed:
silenceCeilingDb | What it says | What to do |
|---|---|---|
Near 0 | A take never stops sounding; no threshold can open a gap in it | Take the cut points from something other than silence: a marker, a beat |
Below topDb | The threshold was too loose to see the quiet these takes do have | Re-run with a topDb under the reported ceiling; that figure cuts |
At or above topDb, and still one interval | Every take goes quiet at this setting, but never in the same place | The takes are out of time with each other — align them first (below) |
The two interval counts describe shape, not cause: a take that sounds once and stops counts 1 exactly as a take with no silence does, so use them to see whether any take has an interior gap at all (maxSignalIntervals >= 2) and whether the takes differ in how broken up they are — the ceiling carries the verdict. silenceCeilingDb is 0 for an all-silent take, where the peak is zero and the ratio has no value. All three figures come from the same RMS pass as the intervals, so they never describe a different measurement. The plain splitSilenceCommon stays for a caller who is only cutting; both entry points share their defaults (topDb 60, frameLength 2048, hopLength 512) and their refusals — an empty signals list or an empty take throws from either.
Slice every channel on the same frames
For a mono take, take.subarray(start, end) over each interval is the whole job. A stereo take has one more step. remix can snap a cut point to a zero crossing so a slice does not start on a click, but snapping is a per-signal decision: run it channel by channel and each channel snaps to a different frame, and the stereo image drifts apart at every cut. remixAlignedIntervals resolves the snapped cut set from one channel, without cutting, and returns one clamped (start, end) pair per input interval so the same frames can be applied to every channel:
import { remixAlignedIntervals } from '@libraz/libsonare';
const cuts = remixAlignedIntervals({
samples: takeLeft, // resolve from one channel only
intervals, // the shared intervals from the split above
sampleRate, // validated, so pass the real rate
alignZeros: true, // the default; false clamps the intervals without snapping
});
for (let i = 0; i < cuts.length; i += 2) {
const left = takeLeft.subarray(cuts[i], cuts[i + 1]);
const right = takeRight.subarray(cuts[i], cuts[i + 1]); // identical frames
}cuts = sonare.remix_aligned_intervals(take_left, sample_rate, intervals, align_zeros=True)
for start, end in cuts: # (n, 2): one row per interval
left = take_left[start:end]
right = take_right[start:end] # identical framesTwo guards keep a slice from vanishing: a channel with no sign change at all (silence, a DC offset, any constant) is not snapped, and a slice that had content but would collapse to empty after snapping keeps its unsnapped boundaries. With alignZeros: false the pairs are simply the inputs clamped to the buffer. Note what this call consumes: the intervals from the silence split, in sample positions of the take's own buffer — not the anchors from the alignment below, which describe the project timeline.
Aligning a take that drifts
When the report puts the ceiling at or above topDb and still returns one interval, the takes each go quiet but never together: they are out of time with each other, and no threshold fixes that. alignTakeToReference measures a chromagram (the twelve pitch classes over time) for the reference and for the take, aligns the two with dynamic time warping (DTW: it finds the cheapest path pairing each moment of the take with a moment of the reference, letting either side wait), and returns the alignment as project warp anchors, the { warpSample, sourceSample } pairs setWarpMap accepts, already oriented for a clip whose source is the take: warpSample is a position on the reference timeline and sourceSample the matching position in the take. The recording itself is untouched; the clip plays it stretched under the reference.
import { alignTakeToReference, Project } from '@libraz/libsonare';
const { anchors, alignment } = alignTakeToReference({
reference, // Float32Array: the guide take, or the backing track the takes were sung against
take, // Float32Array: the take to place under it
sampleRate, // the reference's rate
// takeSampleRate: 44100, // the take's rate when it differs; defaults to sampleRate
// hopLength: 512, // chroma hop: a smaller hop measures more frames and yields more anchors
// binsPerOctave: 12, // must be a positive multiple of 12; leave it unless checked against the rate
});
// alignment -> { meanResidualFrames, referenceFrames, takeFrames } — descriptive, never a failure
const project = new Project();
try {
project.setSampleRate(sampleRate);
const trackId = project.addTrack({ kind: 'audio', name: 'take 2' });
const clipId = project.addClip({ trackId, startPpq: 0, lengthPpq: 8, channels: [take], sampleRate });
project.setWarpMap({ id: 1, name: 'take 2 under guide', anchors });
project.setClipWarpRef(clipId, 1);
project.setClipWarpMode(clipId, 'timeStretch'); // follow the anchors, keep the pitch
} finally {
project.destroy();
}import libsonare as sonare
result = sonare.align_take_to_reference(reference, take, sample_rate)
# take_sample_rate=, hop_length= and bins_per_octave= are keyword-only
anchors, alignment = result.anchors, result.alignment # (warp_sample, source_sample) tuples
with sonare.Project() as project:
project.set_sample_rate(sample_rate)
track_id = project.add_track("audio", "take 2")
clip_id = project.add_clip(track_id, 0.0, 8.0, audio=take, audio_channels=1, audio_sample_rate=sample_rate)
project.set_warp_map(1, anchors, name="take 2 under guide")
project.set_clip_warp_ref(clip_id, 1)
project.set_clip_warp_mode(clip_id, "timeStretch")A warp map belongs to a clip, so each aligned take gets its own clip and its own map. Once they all play in time under the reference, cut the comp on that shared timeline with splitClip and trims; a 'timeStretch' clip takes the new map from the next audio block with no re-bake. The anchors are already reduced to the strictly increasing form a warp map requires (a DTW path holds one axis still wherever the two recordings differ in speed, and a run of tied coordinates is represented by its middle anchor), so the result goes into setWarpMap as it is.
alignment describes how the pair was conditioned. None of these figures fails the call; a caller deciding what is acceptable supplies its own threshold.
takeFrames / referenceFramesis the overall rate difference the anchors encode.meanResidualFramesis the mean absolute departure of the path from its own diagonal trend: a coarse indication of how much the take disagrees with the reference, not an error bound.
What is refused, and how
A take that cannot be aligned is reported, never answered with a map you cannot use. Two layers refuse, and which one answers decides what you are told:
- Named by field, before the measurement. An empty buffer (
reference must not be empty,take must not be empty), a non-finite sample (reference contains a non-finite sample at index N, and the same fortake), asampleRateortakeSampleRatethat is not an integer in[8000, 384000], ahopLengthoutside[1, 65536], and abinsPerOctavethat is not a positive multiple of 12 (each pitch class is the mean of a whole number of CQT bins; CQT is the constant-Q transform, a spectrum with log-spaced bins, so 13 and 18 have no fold) all throw aRangeErrorthat names the offending field. A value that is not a number at all throws aTypeError. - From the measurement. A pair that yields no two distinct anchors — either recording shorter than one chroma frame is what that looks like — throws a
RangeErrorwhose message is onlyInvalid parameter: the core reports the condition without naming an argument.
A multiple of 12 is necessary, not sufficient: the finest usable binsPerOctave depends on the sample rate and does not rise with it, so leave the field at its default unless a finer grid has been checked at the rate it will run at. Omit either field to select the library value; an explicit 0 is refused.
Sample rates:
sampleRateis the reference's rate andtakeSampleRate(Pythontake_sample_rate, Csonare_align_take_to_reference) the take's. When they differ, the take is resampled onto the reference's grid before measuring.- Both anchor axes come back in samples at the reference rate, and
hopLengthis at that rate too. - A project reads warp anchors in samples at the project rate, so multiply
warpSampleandsourceSampleby the project rate over the reference rate beforesetWarpMap(the example above has them equal). The CLI counterpart,sonare project align-takes, reads the reference and each take from their files, aligns a take at another rate, and writes the anchors at the project rate.
Related
- Recording and Loop Takes — capture, the browser microphone, and splitting loop passes into takes
- Project Editing — clips, PPQ, fades, warping, and the edit compiler that renders comps
- JavaScript API — signatures for
alignTakeToReference,remixAlignedIntervals, andsplitSilenceCommonWithReport - Bouncing Projects — render the comped arrangement offline