defineSound

Takes a sound definition and returns a function that plays it. Call the function to trigger the sound - each call returns a VoiceHandle for stopping mid-flight.

import { defineSound } from "@web-kits/audio";

const play = defineSound({
  source: { type: "sine", frequency: 440 },
  envelope: { decay: 0.1 },
  gain: 0.3,
});

const voice = play();
voice.stop(0.1);

Signature

function defineSound(definition: SoundDefinition): (opts?: PlayOptions) => VoiceHandle;

PlayOptions

Override volume, panning, or pitch at play time without changing the definition.

PropertyTypeDescription
volumenumberGain multiplier
pannumberStereo pan (-1 to 1)
detunenumberPitch offset (cents)
playbackRatenumberSpeed multiplier
velocitynumberIntensity (0–1)
jitterobjectPer-voice random variation (see below)
play({ velocity: 0.5, pan: -0.3, detune: 100 });

Jitter

Give repeated triggers a little life. jitter randomizes chosen parameters once per voice, so the same sound never plays exactly the same way twice. Each field is the maximum symmetric offset (±value).

PropertyTypeDescription
detunenumberRandom pitch in cents (e.g. 50 = ±50 cents)
volumenumberRandom gain offset (e.g. 0.1 = ±10%)
playbackRatenumberRandom rate offset (e.g. 0.05 = ±5%)
const click = defineSound({
  source: { type: "sine", frequency: 1800 },
  envelope: { decay: 0.06 },
  gain: 0.3,
});

<button onClick={() => click({ jitter: { detune: 60 } })}>Click</button>

VoiceHandle

MethodDescription
stop()Stop with a short default fade
stop(0.5)Fade out over 500ms