AudioBits

Recipes

Define a reusable sound with bounded versioned JSON data.

AudioBits API · 0.7.0 · Available on npm.

A recipe is data, not a native graph or code. defineSound() throws on invalid data and returns a deeply frozen snapshot. validateRecipe() returns path-specific issues without throwing for invalid input. Both work without browser globals. validateRecipe(unknown) returns { ok: true, recipe } or { ok: false, issues }. Each issue has code, path, and message; paths use JSON bracket notation such as $["layers"][0]["id"]. Inputs must be plain JSON data. The snapshot is copied, so later input mutations cannot change an existing definition.

import { defineSound, validateRecipe } from "audiobits";
const input: unknown = {
  schemaVersion: 1,
  kind: "one-shot",
  duration: 0.15,
  layers: [
    {
      id: "tone",
      source: { type: "oscillator", waveform: "sine", frequency: 660 },
      gainDb: -18,
      envelope: { attack: 0.004, decay: 0.08, sustain: 0.1, release: 0.04 },
    },
  ],
};
const result = validateRecipe(input);
if (result.ok) {
  const recipe = defineSound(result.recipe);
  console.log(recipe.kind);
} else {
  for (const issue of result.issues) console.error(issue.path, issue.message);
}

Catalog source you own

Catalog recipe items have canonical source in catalog/recipes/. Install an individual recipe through the catalog source guide, import its local recipe.ts, create a sound, and play it after gesture activation. You own that source. The npm package supplies only the engine and recipe language. See Quick start for a complete local recipe using public engine APIs.

Interactive source

Energy Charge, Reactive Thruster, and Lightsaber combine portable recipe data with application-driven sound controllers. Installed source excludes browser hosts and visual renderers. Reactive Thruster's recipe is separate from the simpler catalog thruster. See catalog integration for file layout, controller ownership, and adapting these experiences to your application.

Independent oscillator pitch offset

An oscillator's optional detune accepts a number or a play/live mapping in cents (-4800..4800, default 0). It has no automation or random-value form. The authored frequency curve stays intact while detune changes smoothly through voice.set(). Effective pitch is frequency * 2 ** (detune / 1200). All combinations of declared frequency and detune extrema must stay in 20..20000 Hz and below the context's Nyquist limit, including overlapping ramps. The bounds are conservative even for mappings that share a control. Live controls inside frequency automation remain unsupported.

Check the runtime's oscillator-detune capability and recipe.oscillatorDetune metadata. This additive schema-1 field is rejected by older runtimes. The Synth lead workbench exposes a neutral-zero live bend of -200..200 cents while retaining its authored 50 ms pitch scoop.

Supported subset

Schema version 1 supports one-shot gates up to 60 seconds or sustained playback without duration, 1–16 layers with unique IDs, four oscillator waveforms, white noise, fixed ADSR envelopes, frequency automation, lowpass/highpass/bandpass filters, and native delay. Layer gains are -60–0 dB; frequencies are 20–20000 Hz and must be below the context's Nyquist frequency at play time. Effects are limited to eight across the recipe; frequency automation to 128 points. Gain automation, expression strings, file fetches, and sequencing are unsupported.

One-shot duration ends the gate, excluding release and bounded effect tails. Attack and decay must fit within the gate, including the minimum effective attack; zero decay ramps directly to sustain. Frequency automation begins at zero, uses increasing times, and ends by gate close. Sustained automation is an onset sequence of at most 60 seconds, then holds its final value. All mapping and variation extrema must satisfy target bounds and playback Nyquist checks. Noise requires integer context sample rates from 8000 through 192000 Hz; unsupported rates fail with noise-rate before voice allocation.

Validation rejects unknown fields and versions, non-finite numbers, accessors, cycles, depth beyond 16, more than 10000 visited values, and invalid parameter references. Diagnostics are capped at 100. See Parameters for mappings and live controls. The exported recipeSchema and audiobits/schema.json describe the published schema version 1 structure.

The Workbench editor is documented in Catalog.

Typed authoring preserves recipe structure, parameter names and parameter modes. Runtime validation remains authoritative for exact schema validity.

Layer start offsets

Use optional startOffset seconds to leave silence before a layer's crisp onset. It accepts a finite number from 0 to 60, defaults to 0, and is scheduled through the audio clock relative to the voice's start, including play({ at }).

import { defineSound } from "audiobits";

export const mechanicalImpact = defineSound({
  schemaVersion: 1,
  kind: "one-shot",
  duration: 0.1,
  layers: [
    {
      id: "impact",
      source: { type: "noise", color: "white" },
      gainDb: -24,
      envelope: { attack: 0.002, decay: 0.02, sustain: 0, release: 0.01 },
    },
    {
      id: "bolt-return",
      startOffset: 0.045,
      source: { type: "noise", color: "white" },
      gainDb: -32,
      envelope: { attack: 0.002, decay: 0.03, sustain: 0, release: 0.01 },
    },
  ],
});

The source, envelope and layer frequency automation (including layer filters) use the layer onset as time zero. Recipe effects retain voice time zero. One-shot duration remains the shared gate-close time: offset plus effective attack (at least 2 ms) plus decay must fit within it. Layer automation must end by duration - startOffset. Release begins at the shared gate; offsets do not extend the gate or add another allowance to effect tails.

Sustained recipes still run until stopped. Their layer automation, including the offset, must finish within the first 60 seconds of the voice, then holds its final value. A numeric frequency needs no automation sequence.

Stopping at or before a layer onset cancels that pending layer while audible layers release normally. Scheduled stops, Stop All, voice stealing and disposal also cover pending layers. Every layer is owned and counted within its voice from reservation; voice.ended waits for the owned graph and effect tails. Live updates before onset retarget the smoothed ramp scheduled at that layer onset. Updates after onset retain ordinary smoothing. Offsets have no live, parameter-mapping, random or looping form.

Start offsets schedule a layer's source. The delay effect processes its input signal and can repeat it; a wet-only delay with zero feedback shifts the whole signal, including release. Check layer-start-offset in runtime capabilities and recipe.layerStartOffset in metadata. This additive schema-1 field is rejected by older runtimes.

Delay

Add delay to a recipe's effects to process its summed layers, or to a layer's effects to echo only that layer. Effects run in array order.

import { createAudio, defineSound } from "audiobits";

const audio = createAudio();
const ping = audio.sound(
  defineSound({
    schemaVersion: 1,
    kind: "one-shot",
    duration: 0.08,
    layers: [
      {
        id: "ping",
        source: { type: "oscillator", waveform: "sine", frequency: 660 },
        gainDb: -18,
        envelope: { attack: 0.004, decay: 0.06, sustain: 0.1, release: 0.04 },
      },
    ],
    effects: [{ type: "delay", time: 0.24, feedback: 0.3, mix: 0.25 }],
  }),
);

let request = 0;
export async function play() {
  // Call from a user gesture.
  const token = ++request;
  await audio.start();
  if (token === request) ping.play();
}
export function stop() {
  request++;
  audio.stopAll({ tails: "cut" });
}
export async function dispose() {
  // Call on host teardown.
  request++;
  await audio.dispose();
}
ParameterRangeDefaultMeaning
time0.01–2 secondsRequiredSpacing between echoes
feedback0–0.80Fraction of each echo fed back; 0 produces one echo
mix0–10.5Linear blend: dry gain 1 - mix, wet gain mix

All three accept a number, seeded variation, or a mapping to a mode: "play" parameter. They resolve once at play time. Delay does not accept automation points or live mappings. Existing live source, gain and filter controls still work alongside delay. At unusually low sample rates, feedback delay must also be at least 256 / sampleRate seconds; playback rejects shorter values with delay-time instead of silently changing the echo spacing.

The first echo has gain mix; each later echo multiplies that gain by feedback. There is no automatic normalization or limiter. Overlapping echoes can reinforce a sustained tone: wet gain can approach mix / (1 - feedback). Leave headroom for feedback, serial effects, filters and overlapping voices. mix: 0 bypasses the delay without allocating a delay line or extending lifetime.

Layer filters before the first audible delay keep their existing placement before the envelope. That delay and all following layer effects process the released signal. Recipe effects process the sum after layer envelopes and effects. This preserves filter-only recipes and lets layer echoes survive release.

A natural one-shot or voice.stop() allows the release and echo tail to finish. Tail budgeting includes repeats down to 0.001 of the first echo's amplitude (−60 dB), adds serial effect allowances, and caps each layer-to-output path at 30 seconds after release, followed by a 50 ms fade. The cap can truncate long or cascaded feedback tails; it is a resource deadline, not a silence detector. voice.ended settles after the entire owned graph is disconnected, and tails continue to occupy voice capacity. audio.stopAll({ tails: "cut" }) and voice stealing fade the complete output in 5 ms. Suspension, sound/bus disposal and engine disposal immediately finalize owned tails, even when the audio clock stops. Repeated Stop cannot extend a deadline; stopping before a scheduled onset cancels it.

Delay is additive within schema version 1. Older runtimes reject this effect; check recipe.effects in audiobits/capabilities.json for "delay" when exchanging recipes across runtime versions. Damping, live delay modulation and shared bus effects are not supported. Place an ordinary filter before or after delay for input or output tone shaping; it does not filter each feedback circulation.

On this page