Skip to content

Record Audio Takes: Microphone, Punch-In, Loops ​

This page is about getting live sound into a project. Recording is capturing live audio — a vocal, a guitar DI (plugged in directly, no amp mic), a synth performance — into a buffer you can keep, edit, and arrange. When you record the same part several times as alternate takes, Comping Takes is the next step: assembling one keeper by stitching the best moments of each take together.

libsonare splits this into two cooperating pieces. The realtime engine owns the live capture path — arming, the capture buffer, input monitoring, and punch in/out (re-record only a chosen region, leaving the rest of the take untouched). The project model owns the result — clips that carry takes, which Comping Takes turns into one performance.

What You Will Learn ​

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

  • configure the engine's capture (buffer, source, record offset, monitoring, punch window), arm it, and read captured audio back;
  • compensate for round-trip latency with a record offset and hear yourself with input monitoring;
  • punch in and out so only a chosen region is recorded;
  • open a browser microphone with bindMicrophoneInput and clean it up correctly;
  • split a captured loop into takes with addLoopRecordingTakes;
  • draw the recorded waveform with waveformPeaks and waveformPeakPyramid.

Two clocks, two layers

The capture path works in samples on the audio thread. The project works in PPQ (musical position): one PPQ unit is one quarter note, so at 120 BPM ppq: 1 lasts 0.5 s. You record in samples, then describe the result in beats. Keep the two straight and everything below falls into place.

Where recording sits in the pipeline

Recording gets audio in. Editing fixes its timing and pitch. Mixing balances several tracks. Mastering polishes the stereo result. This page covers the first step; Comping Takes turns a pile of takes into one usable clip, and Project Editing takes it from there.

From microphone to comped clip ​

Recording crosses the realtime layer and the project layer. The engine captures samples; the project stores those samples as takes and comp instructions. The two halves meet at a single handoff point — capturedAudio() — which is also where you must switch from the audio thread to the main/control thread.

Capture-to-bounce pipeline
REALTIME ENGINEPROJECT MODELMic or engine outputCapture buffercapturedAudio()addLoopRecordingTakesClip takesComp segmentscompile() / bounce()
capturedAudio() is the one safe crossing point from the audio thread to the main/control thread.

Do not put Project editing calls in the audio callback. Capture in the realtime engine first, then update the project from the main/control thread after the take is finished.

The capture path ​

The realtime engine records into a capture buffer you allocate up front. Nothing is captured until you both allocate the buffer and arm capture; each process(...) block then appends to it while armed.

The engine runs in Node, so the whole capture path below is testable outside the browser. Only the microphone section needs a browser.

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

await init();

const sampleRate = 48000;
const engine = new RealtimeEngine({ sampleRate, maxBlockSize: 128 });
try {
  engine.configureCapture({ numChannels: 2, capacityFrames: sampleRate * 10 }); // room for 10 s
  engine.armCapture({ armed: true }); // start appending on the next processed block
  engine.play();

  // Process the engine block by block (in a real app this is your audio callback).
  engine.process([blockL, blockR]);

  const status = engine.captureStatus();
  // { capturedFrames, droppedFrames, armed, punchEnabled, source, recordOffsetSamples }

  const channels = engine.capturedAudio(); // Float32Array[] — one array per channel
} finally {
  engine.destroy();              // the WASM handle is NOT garbage-collected — always release it
}
python
import libsonare as sonare

engine = sonare.RealtimeEngine(sample_rate=48000, max_block_size=128)
try:
    engine.configure_capture(num_channels=2, capacity_frames=48000 * 10)   # room for 10 s
    engine.arm_capture()
    engine.play()

    engine.process([block_l, block_r])         # in a real app, your audio callback

    status = engine.capture_status()
    # status.captured_frames, dropped_frames, armed, punch_enabled, source, record_offset_samples

    channels = engine.captured_audio()         # list of arrays, one per channel
finally:
    engine.close()

Always release the engine

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

Sizing the capture buffer ​

configureCapture(options) sets the buffer, source, record offset and punch window. An omitted field uses its default. Omit punch to clear the window. Set the input monitor separately with setInputMonitor. Preallocate the recording using capacityFrames and numChannels, which defaults to 2. Changing either while capture is armed raises a SonareError with code InvalidState. Size the buffer for the longest take with capacityFrames = seconds * sampleRate. When the buffer fills, captureStatus().droppedFrames counts the discarded frames.

Arming and capture status ​

armCapture({ armed }) toggles recording: armCapture({ armed: true }) arms, and armCapture({ armed: false }) stops appending without discarding what you have (Python arm_capture(armed=True)). resetCapture() clears the captured frames back to zero so the next take starts fresh. Read progress any time with captureStatus():

FieldTells you
capturedFramesHow many frames are recorded so far
droppedFramesFrames discarded because the buffer was full since the last reset (0 is healthy)
armedWhether the engine is currently appending
punchEnabledWhether a punch in/out region is active
source'output' or 'input' — what is being captured
recordOffsetSamplesThe active record-offset compensation

Capture source: output bus vs live input ​

The source option ('output' or 'input') chooses what the engine records:

  • 'output' (the default) captures the engine's rendered output bus — what you would hear, including any clips and instruments the engine is playing. Use it to bounce a live performance of the arrangement.
  • 'input' captures the raw audio you pass into process(...) — the live signal from a microphone or instrument. Use it to track a new part.

Record-offset compensation ​

A live monitoring chain has latency: by the time a player hears the click and plays a note, the engine has already advanced. The recordOffsetSamples option (default 0) moves the capture window along the stream you pass to process. A positive value delays capture: with a punch window of [start, end), the recording covers [start + offsetSamples, end + offsetSamples). When the performer's audio reaches the engine late by the round-trip latency, use a positive offset equal to that latency. The active value is echoed back in captureStatus().recordOffsetSamples. In a loop every pass stays whole: input that arrives within the offset after a wrap is captured at the end of the previous pass.

No punch window, no effect

The offset acts on the punch window, so without one it changes nothing.

Input monitoring ​

setInputMonitor({ enabled: true, gain: 0.5 }) mixes the live input into the output at half level. Use setInputMonitor({ enabled: false }) when the performer monitors through hardware. The gain defaults to 1. Input monitoring is independent of the capture source.

Punch in/out ​

Punch recording arms capture only inside a chosen timeline region, so a fixed take is left untouched outside it. While punchEnabled is true, the engine appends only when the transport (the moving play position) is inside [startSample, endSample).

Spellingpunch option
Samples{ startSample, endSample }
Seconds{ startSec, endSec }, rounded to the nearest sample at the engine's sample rate
Quarter notes{ startPpq, endPpq }
Pythonpunch=CapturePunch(start_sample=..., end_sample=...), or the _sec / _ppq fields

Give one spelling per bound, and both bounds: a negative bound, both spellings of one bound, or a zero-length range throws a RangeError, and a missing bound a TypeError (Python SonareValueError). Omit punch to clear the region and return to free recording. resetCapture() empties the buffer but keeps the punch window.

Track a part, then read it back
typescript
const engine = new RealtimeEngine({ sampleRate: 48000, maxBlockSize: 128 });
try {
  engine.configureCapture({
    numChannels: 1,
    capacityFrames: 48000 * 8,              // mono, up to 8 s
    source: 'input',                        // record the live signal, not the mix
    punch: { startSec: 0, endSec: 8 },
    recordOffsetSamples: 256,               // input arrives ~256 frames late, so capture 256 frames later
  });
  engine.setInputMonitor({ enabled: true, gain: 1 });
  engine.armCapture({ armed: true });
  engine.play();

  // ... pass live input blocks via engine.process([micBlock]) ...

  const [mono] = engine.capturedAudio();    // the recorded take as a Float32Array
} finally {
  engine.destroy();
}

Browser microphone input ​

In the browser, bindMicrophoneInput(audioContext, engine, options?) wires a getUserMedia microphone stream into a realtime engine node and returns a binding you can destroy. It is browser-only — it needs a live AudioContext and the Web Audio graph — and runs without SharedArrayBuffer (no COOP/COEP headers required).

typescript
// Browser only — runs inside a page with a live AudioContext.
const binding = await bindMicrophoneInput(audioContext, engineNode, {
  // Any MediaStreamConstraints field is forwarded to getUserMedia:
  audio: { echoCancellation: false, noiseSuppression: false, channelCount: 1 },
  // Optionally reuse a stream you already opened:
  // stream: existingMediaStream,
  stopTracksOnDestroy: true, // default; stop the mic tracks when you destroy the binding
});

// binding.stream  -> the live MediaStream
// binding.source  -> the MediaStreamAudioSourceNode connected to the engine

// When the take is done:
binding.destroy();           // disconnects the source (and stops tracks if stopTracksOnDestroy)

The options object extends MediaStreamConstraints, so any constraint you would pass to getUserMedia (the audio object with echoCancellation, noiseSuppression, channelCount, a device deviceId, …) goes straight through. Two extra fields are libsonare's own:

  • stream — reuse a MediaStream you already obtained instead of prompting for a new one.
  • stopTracksOnDestroy — defaults to true. When true, binding.destroy() also stops the underlying microphone tracks, turning off the OS recording indicator. Set it to false when you pass a stream you own and want to keep using elsewhere.

Destroy the binding when you are done

binding.destroy() disconnects the source node so the microphone stops sending audio to the engine. Pair every bindMicrophoneInput with a destroy() — typically when the user stops recording or the component unmounts. The default also stops microphone tracks so the OS recording indicator goes away; pass stopTracksOnDestroy: false only when another part of your app still needs the same stream.

For the surrounding AudioWorklet plumbing — building the engine node, registering the worklet processor, and the SAB-free (SharedArrayBuffer-free) realtime path — see Realtime Streaming. To play a synth or sampler into the recording instead of an external mic, see Native Synth and the SoundFont Player, and MIDI Input for driving them live.

Loop recording into takes ​

Loop recording cycles the same musical region over and over while you play, capturing one take per pass. Project.addLoopRecordingTakes(desc) takes the concatenated captured audio for all passes and splits it into per-pass takes on a single new clip:

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

await init();

const project = new Project();
try {
  const sampleRate = 48000;
  project.setSampleRate(sampleRate);
  const trackId = project.addTrack({ kind: 'audio', name: 'vocal' });

  // A 4-quarter-note loop at 120 BPM lasts 4 * (60 / 120) = 2 s.
  // Three passes therefore need 3 * 2 s of audio.
  const loopLengthQuarters = 4;
  const passes = 3;
  const passSamples = Math.round((loopLengthQuarters * 60 / 120) * sampleRate); // 96000
  const recorded = new Float32Array(passes * passSamples);                       // your concatenated passes (interleaved if audioChannels > 1, or one array per channel)

  const result = project.addLoopRecordingTakes({
    trackId,
    startPpq: 0,
    loopLengthPpq: loopLengthQuarters,   // loop length in quarter notes
    audio: recorded,
    audioChannels: 1,
    audioSampleRate: sampleRate,
  });
  // result -> { clipId, takeCount: 3 }
} finally {
  project.destroy();
}
python
import libsonare as sonare
import numpy as np

sample_rate = 48000
with sonare.Project() as project:
    project.set_sample_rate(sample_rate)
    track_id = project.add_track("audio", "vocal")

    # A 4-quarter-note loop at 120 BPM lasts 2 s, so three passes need 3 * 2 s.
    loop_length_quarters = 4.0
    passes = 3
    pass_samples = round(loop_length_quarters * 60 / 120 * sample_rate)   # 96000
    recorded = np.zeros(passes * pass_samples, dtype=np.float32)          # your concatenated passes

    takes = project.add_loop_recording_takes(
        track_id, 0.0, loop_length_quarters, recorded,
        audio_channels=1, audio_sample_rate=sample_rate, partial_tail="keep",
    )   # takes.clip_id, takes.take_count == 3

Node uses the same calls as the browser tab.

Supply enough audio for the takes you claim

loopLengthPpq is measured in quarter notes, so its duration depends on tempo: a 4-quarter-note loop is 2 s at 120 BPM but 4 s at 60 BPM. Set the project tempo first, work out the per-pass sample count from it, and supply passes * passSamples frames. Hand in less and you simply get fewer takes than you expected.

Interleaved or planar audio

audio takes either shape. A single Float32Array is read as interleaved when audioChannels > 1 (L, R, L, R, …). An array of Float32Arrays — one per channel, all the same length, the shape engine.capturedAudio() returns — is read as planar: its length is the channel count and audioChannels is ignored. Python takes a channels-first 2-D array or a sequence of equal-length per-channel sequences the same way.

The call adds one clip whose alternate takes are the loop passes, and sets the active take to the newest (last) pass. If your captured audio did not end exactly on a loop boundary, the last pass is a short, partial take. It is kept, but it is not activated: the previous complete take stays active, and the partial take carries "partial": true in its entry of the project JSON takes, which round-trips. A capture shorter than one loop has only the partial take, and that take stays active. A remainder of one frame or less creates no take.

Pass partialTail: 'drop' (Python partial_tail="drop") to leave the partial take out altogether; the default is 'keep'. In the example above, 2 full passes plus 30000 frames give takeCount: 3 with take 2 active and take 3 marked partial, and 'drop' gives takeCount: 2. From here you comp across those takes (Comping Takes).

Comping the takes ​

Choosing which take plays where, softening the seams, and cutting free takes at shared points are on Comping Takes.

Drawing the recorded waveform ​

To draw a take you do not plot every sample — you reduce the audio to per-bucket min/max pairs and draw those as a filled envelope. waveformPeaks({ channels, samplesPerBucket? }) does the reduction from planar audio, one Float32Array per channel.

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

await init();

// Planar stereo: one array per channel.
const left = new Float32Array([-1.0, 0.25, 0.75, -0.5, 0.0]);
const right = new Float32Array([0.5, -0.25, 0.1, -0.75, 0.9]);

const report = waveformPeaks({ channels: [left, right], samplesPerBucket: 2 });
// report = {
//   bucketCount: 3,
//   samplesPerBucket: 2,
//   min: [Float32Array [ -1, -0.5, 0 ], Float32Array [ -0.25, -0.75, 0.9 ]],
//   max: [Float32Array [ 0.25, 0.75, 0 ], Float32Array [ 0.5, 0.1, 0.9 ]],
// }
python
import numpy as np
import libsonare as sonare

left = np.array([-1.0, 0.25, 0.75, -0.5, 0.0], dtype=np.float32)
right = np.array([0.5, -0.25, 0.1, -0.75, 0.9], dtype=np.float32)
interleaved = np.stack([left, right], axis=1).reshape(-1)   # Python takes interleaved samples

report = sonare.waveform_peaks(interleaved, 2, samples_per_bucket=2)
# report.bucket_count == 3; report.min and report.max are flat, channel 0's buckets then channel 1's:
# bucket b of channel c is report.min[c * report.bucket_count + b]
pyramid = sonare.waveform_peak_pyramid(interleaved, 2, samples_per_bucket_levels=[2, 4])   # a list of reports

min and max hold one array per channel, each with bucketCount values, so bucket b of channel c is report.min[c][b]. When samplesPerBucket is omitted it defaults to 512 frames per bucket.

For a zoomable view, waveformPeakPyramid({ channels, samplesPerBucketLevels? }) returns one report per zoom level instead of one report:

typescript
const pyramid = waveformPeakPyramid({ channels: [left, right], samplesPerBucketLevels: [2, 4] });
// pyramid.length === 2
// pyramid[0].samplesPerBucket === 2  (finer — more buckets, zoomed in)
// pyramid[1].samplesPerBucket === 4  (coarser — fewer buckets, zoomed out)

Each level is a full WaveformPeaksReport. With no options the pyramid uses the standard zoom set [512, 1024, 2048, 4096] frames per bucket, so you can swap detail levels as the user zooms without recomputing peaks on every frame: precompute the pyramid once and pick the level closest to the current pixels-per-second, since coarser levels have fewer buckets and are cheaper to draw when zoomed out. To draw a level, stroke one vertical line per bucket from min[c][b] to max[c][b]. Both calls are batch reductions for a buffered clip, not audio-callback work.

Drawing from captured audio

capturedAudio() returns planar channels (one Float32Array each), the shape waveformPeaks takes, so pass the array straight in as channels: waveformPeaks({ channels: engine.capturedAudio() }).

Recipes ​

Capture the output bus and draw it

Record a live pass of the arrangement, then reduce it to a drawable waveform.

typescript
const engine = new RealtimeEngine({ sampleRate: 48000, maxBlockSize: 128 });
try {
  engine.configureCapture({
    numChannels: 2,
    capacityFrames: 48000 * 30,              // stereo, up to 30 s
    source: 'output',                        // capture the rendered mix
  });
  engine.armCapture({ armed: true });
  engine.play();
  // ... call engine.process([...]) for the performance ...

  const peaks = waveformPeaks({ channels: engine.capturedAudio() }); // 512-frame buckets by default
  // peaks.min / peaks.max -> envelope for your canvas
} finally {
  engine.destroy();
}

Once a take is captured and comped, it lives on a clip in your project like any other audio. From here you arrange and trim it in Project Editing, then turn the finished arrangement into a file in Bouncing Projects.