Sound engine
Sixteen short interface sounds in one key, synthesised in the browser with no audio files, levelled and limited. Off until the visitor turns it on.
Install
npx shadcn@latest add https://thrumui.dev/r/thrum-sound.jsonAdds lib/thrum-sound.ts. Nothing else in your project changes.
import { soundDuration } from "@/lib/thrum-sound";Source
"use client";
/**
* UI sound. Every sound is synthesized with the Web Audio API: no audio files, no dependencies.
*
* - Off by default. The choice is saved in localStorage and shared by every component on the page.
* - Nothing touches Web Audio until sound is on and the visitor has interacted with the page.
* - Safe to import on the server: every call is a no-op there.
*
* The system, in one place:
* - Pitch: every tone is a note of D major pentatonic (D E F# A B) between B4 and E6, so overlapping sounds stay
* consonant and a laptop speaker plays every fundamental. Rising means on, open, added, done; falling means the reverse.
* - Timbre: three recipes. `pluck` (a sine with a soft octave, struck and left to ring down) carries every pitch,
* `click` (a short burst of band-passed noise) marks a moment, `air` (a noise sweep) marks movement.
* - Kinds: `micro` sounds repeat during one gesture and last at most 40 ms; `control` sounds answer one action and
* last at most 200 ms; `notice` sounds report an outcome and last at most 400 ms.
* - Loudness: each sound is trimmed (its first number below) to a target in LUFS, measured as the loudest 400 ms
* at the default volume. Controls sit at -34; micro sounds well below; notices above, ranked success < warn < error.
* - Playback: each play varies pitch and level slightly; a sound repeated quickly is dropped or played softer;
* at most six sounds ring at once; and a soft limiter after the volume keeps any stack from clipping.
*/
import { useSyncExternalStore } from "react";
export type Layer = {
kind: "tone" | "noise";
/** Tone pitch, or noise filter frequency, in Hz. */
freq: number;
/** Start at this frequency and glide to `freq` over `ms`. */
from?: number;
ms?: number;
/** Noise only: band-pass (a click or air) or low-pass (a thud). */
filter?: "bp" | "lp";
q?: number;
/** Start offset in ms. */
at?: number;
/** Attack time in ms. */
attack: number;
/** Decay time constant in ms. The layer is silent after about seven of these. */
tau: number;
/** Peak linear gain. */
peak: number;
};
const tone = (freq: number, attack: number, tau: number, peak: number, extra: Partial<Layer> = {}): Layer => ({ kind: "tone", freq, attack, tau, peak, ...extra });
const noise = (freq: number, q: number, attack: number, tau: number, peak: number, extra: Partial<Layer> = {}): Layer => ({ kind: "noise", filter: "bp", freq, q, attack, tau, peak, ...extra });
/** The one pitched timbre: a sine and a soft octave above it, struck in 2 ms and left to ring down. */
const pluck = (freq: number, tau: number, peak: number, extra: Partial<Layer> = {}): Layer[] => [
tone(freq, 2, tau, peak, extra),
tone(freq * 2, 2, tau / 2, peak * 0.2, { ...extra, from: extra.from && extra.from * 2 }),
];
/** A moment: a short burst of noise around 1.2 to 2 kHz, below the range where clicks turn piercing. */
const click = (freq: number, peak: number, extra: Partial<Layer> = {}): Layer => noise(freq, 1.5, 1, 2.5, peak, extra);
/** Movement: band-passed noise sweeping from one frequency to another. */
const air = (from: number, to: number, attack: number, tau: number, peak: number): Layer => noise(to, 1.2, attack, tau, peak, { from, ms: attack + tau });
/** Scale a sound by `db` decibels. This is the loudness trim: it brings each sound to its target. */
const trim = (db: number, layers: Layer[]): Layer[] => layers.map((l) => ({ ...l, peak: l.peak * 10 ** (db / 20) }));
const B4 = 493.88, D5 = 587.33, E5 = 659.26, A5 = 880, B5 = 987.77, D6 = 1174.66, E6 = 1318.51;
export const SOUNDS = {
/** A detent: the chart cursor lands on a new point, a slider or stepper crosses a step. */
tick: trim(6.4, [click(2000, 0.1), tone(D6, 1, 3, 0.04)]),
/** Barely there. No component plays it by default. */
hover: trim(14.8, [click(1200, 0.05, { attack: 4, tau: 4, q: 3 })]),
/** A choice: a tab, option, row or series is picked. */
select: trim(4.5, [click(2000, 0.05), ...pluck(A5, 16, 0.12)]),
toggleOn: trim(1.6, [click(1800, 0.04), ...pluck(D5, 14, 0.12), ...pluck(A5, 18, 0.12, { at: 40 })]),
toggleOff: trim(1.7, [click(1800, 0.04), ...pluck(A5, 14, 0.12), ...pluck(D5, 18, 0.12, { at: 40 })]),
open: trim(7.1, [air(700, 1800, 25, 18, 0.06), ...pluck(A5, 18, 0.08, { at: 25 })]),
close: trim(7.9, [air(1800, 700, 4, 16, 0.06), ...pluck(D5, 18, 0.08)]),
add: trim(3.4, [click(2000, 0.05), ...pluck(B5, 22, 0.12, { from: E5, ms: 25 })]),
remove: trim(3.7, [click(1400, 0.05), ...pluck(E5, 20, 0.12, { from: B5, ms: 25 })]),
/** An item is picked up to be dragged. */
lift: trim(7.4, [air(900, 1600, 6, 10, 0.05), ...pluck(D6, 12, 0.08)]),
/** A dragged item is set down, moved or not. */
drop: trim(6, [click(1200, 0.08, { tau: 3 }), ...pluck(D5, 12, 0.12)]),
/** An action finished. A rising fourth that resolves on D. */
success: trim(-0.5, [...pluck(A5, 30, 0.12), ...pluck(D6, 40, 0.13, { at: 70 })]),
/** Finished, but needs a look. The same note twice: it asks, it does not resolve. */
warn: trim(1, [...pluck(B5, 30, 0.12), ...pluck(B5, 40, 0.12, { at: 110 })]),
/** A recoverable failure. A falling fourth, low. Calm, not a buzzer. */
error: trim(1.6, [...pluck(E5, 30, 0.13), ...pluck(B4, 40, 0.14, { at: 110 })]),
/** An animated number lands on its value. */
countDone: trim(1.6, [click(2000, 0.04), ...pluck(D6, 30, 0.13)]),
/** A value crosses a marked limit. Ends on an open fifth, so it asks for attention. */
threshold: trim(1.5, [...pluck(A5, 24, 0.11), ...pluck(E6, 36, 0.12, { at: 60 })]),
} satisfies Record<string, Layer[]>;
export type SoundName = keyof typeof SOUNDS;
export type SoundKind = "micro" | "control" | "notice";
/** What each sound is, and how loud it is meant to be: LUFS over its loudest 400 ms at the default volume. */
export const SPEC: Record<SoundName, { kind: SoundKind; lufs: number }> = {
tick: { kind: "micro", lufs: -46 },
hover: { kind: "micro", lufs: -52 },
select: { kind: "control", lufs: -34 },
toggleOn: { kind: "control", lufs: -34 },
toggleOff: { kind: "control", lufs: -34 },
open: { kind: "control", lufs: -34 },
close: { kind: "control", lufs: -34 },
add: { kind: "control", lufs: -34 },
remove: { kind: "control", lufs: -34 },
lift: { kind: "control", lufs: -35 },
drop: { kind: "control", lufs: -34 },
countDone: { kind: "notice", lufs: -33 },
success: { kind: "notice", lufs: -32 },
threshold: { kind: "notice", lufs: -31 },
warn: { kind: "notice", lufs: -31 },
error: { kind: "notice", lufs: -30 },
};
/** The longest each kind may last, from start to silence, in ms. */
export const MAX_MS: Record<SoundKind, number> = { micro: 40, control: 200, notice: 400 };
/** How long a sound lasts from start to silence, in ms. */
export function soundDuration(layers: readonly Layer[]): number {
return Math.max(0, ...layers.map((l) => (l.at ?? 0) + l.attack + 7 * l.tau));
}
// ---------------------------------------------------------------------------------------------
// Playback rules. Pure, so they can be tested without audio.
/** At most this many sounds ring at once. Micro sounds give way earlier, at half. */
export const MAX_VOICES = 6;
/** A sound asked for again sooner than this after itself is dropped, in ms. */
export const MIN_GAP: Record<SoundKind, number> = { micro: 60, control: 80, notice: 80 };
/** A sound repeated within this many ms plays softer, down to half its level, so a fast run never hammers. */
export const SOFTEN_MS = 200;
/** Whether a sound may start, and at what level: 0 drops it, 1 is full. */
export function admit(name: SoundName, sinceLast: number, sounding: number): number {
const kind = SPEC[name].kind;
if (sinceLast < MIN_GAP[kind] || sounding >= (kind === "micro" ? MAX_VOICES / 2 : MAX_VOICES)) return 0;
return Math.min(1, Math.max(0.5, sinceLast / SOFTEN_MS));
}
/** The master limiter's transfer curve: straight up to -8 dBFS, then bending smoothly toward a -1 dBFS ceiling. */
export function softLimit(x: number): number {
const knee = 0.4, room = 0.89 - knee, a = Math.abs(x);
return a <= knee ? x : Math.sign(x) * (knee + room * Math.tanh((a - knee) / room));
}
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function noiseBuffer(ctx: BaseAudioContext): AudioBuffer {
let buffer = noiseBuffers.get(ctx);
if (!buffer) {
buffer = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(ctx, buffer);
}
return buffer;
}
/**
* Schedule a sound's layers on `ctx`, starting at `t0` seconds. Returns the number of layers started.
* Works on a live context and on an OfflineAudioContext, so tests and waveform previews render the real thing.
* `onEnd` runs once, when the last layer has finished.
*/
export function renderLayers(
ctx: BaseAudioContext,
out: AudioNode,
layers: readonly Layer[],
t0: number,
opts: { pitch?: number; level?: number; onEnd?: () => void } = {},
): number {
const pitch = opts.pitch ?? 1;
const level = opts.level ?? 1;
let left = layers.length;
for (const layer of layers) {
const start = t0 + (layer.at ?? 0) / 1000;
const attack = layer.attack / 1000;
const tau = layer.tau / 1000;
const glideEnd = start + (layer.ms ?? 0) / 1000;
// Linear attack from zero, then an exponential approach to zero. This shape cannot click.
const gain = ctx.createGain();
gain.gain.setValueAtTime(0, start);
gain.gain.linearRampToValueAtTime(layer.peak * level, start + attack);
gain.gain.setTargetAtTime(0, start + attack, tau);
gain.connect(out);
const glide = (param: AudioParam) => {
param.setValueAtTime((layer.from ?? layer.freq) * pitch, start);
if (layer.from !== undefined && layer.ms) param.exponentialRampToValueAtTime(layer.freq * pitch, glideEnd);
};
let source: AudioScheduledSourceNode;
let filter: BiquadFilterNode | undefined;
if (layer.kind === "tone") {
const osc = ctx.createOscillator();
glide(osc.frequency);
osc.connect(gain);
osc.start(start);
source = osc;
} else {
const buffer = ctx.createBufferSource();
buffer.buffer = noiseBuffer(ctx);
buffer.loop = true;
filter = ctx.createBiquadFilter();
filter.type = layer.filter === "lp" ? "lowpass" : "bandpass";
// A low-pass Q is in decibels: -3 is flat. A band-pass Q is the usual ratio.
filter.Q.value = layer.filter === "lp" ? -3 : (layer.q ?? 1);
glide(filter.frequency);
buffer.connect(filter).connect(gain);
buffer.start(start, Math.random());
source = buffer;
}
source.stop(start + attack + 7 * tau);
source.onended = () => {
gain.disconnect();
filter?.disconnect();
if (--left === 0) opts.onEnd?.();
};
}
return layers.length;
}
/** The gain for a volume from 0 to 1. Squared, because loudness is not heard in a straight line. */
export const masterGain = (volume: number) => 1.5 * volume * volume;
/** The master chain on `ctx`: volume, then the soft limiter, then the speakers. Sounds connect to `input`. */
export function createOutput(ctx: BaseAudioContext, volume: number): { input: GainNode } {
const input = ctx.createGain();
input.gain.value = masterGain(volume);
// A wave shaper reads its curve over -1 to 1, so the signal goes in at a quarter and the curve covers four times that.
const pad = ctx.createGain();
pad.gain.value = 0.25;
const limiter = ctx.createWaveShaper();
limiter.curve = Float32Array.from({ length: 2049 }, (_, i) => softLimit(((i - 1024) / 1024) * 4));
limiter.oversample = "4x";
input.connect(pad).connect(limiter).connect(ctx.destination);
return { input };
}
// ---------------------------------------------------------------------------------------------
// Live engine: one shared context, created only when sound is on and the page has been used.
const STORE_ENABLED = "thrum:sound";
const STORE_VOLUME = "thrum:sound-volume";
/** A sound requested while audio was still waking up is dropped if it is older than this. */
const STALE_MS = 300;
/** Release the audio device after this many silent milliseconds so the hardware sleeps between interactions. */
export const IDLE_SUSPEND_MS = 1000;
/**
* Detects a frozen hardware audio clock (common on iOS Safari after screen lock/unlock, where `state` reports
* `"running"` while `currentTime` stops advancing).
*/
export function isClockStalled(elapsedWallMs: number, deltaAudioSec: number): boolean {
return elapsedWallMs > 250 && deltaAudioSec <= 0;
}
type State = { enabled: boolean; volume: number };
const SERVER_STATE: State = { enabled: false, volume: 0.8 };
let state: State = SERVER_STATE;
let loaded = false;
let ctx: AudioContext | null = null;
let master: GainNode | null = null;
let sounding = 0;
let idleTimer: ReturnType<typeof setTimeout> | null = null;
let lastWallMs = 0;
let lastAudioTime = 0;
let pending: { name: SoundName; at: number; level: number } | null = null;
const lastPlayed: Partial<Record<SoundName, number>> = {};
const listeners = new Set<() => void>();
function cancelIdle(): void {
if (idleTimer !== null) {
clearTimeout(idleTimer);
idleTimer = null;
}
}
function scheduleIdle(context: AudioContext): void {
cancelIdle();
idleTimer = setTimeout(() => {
idleTimer = null;
if (sounding === 0 && ctx === context && context.state === "running") {
lastWallMs = 0;
void context.suspend().catch(() => {});
}
}, IDLE_SUSPEND_MS);
}
function resetContext(): void {
cancelIdle();
const stale = ctx;
ctx = null;
master = null;
sounding = 0;
lastWallMs = 0;
lastAudioTime = 0;
if (stale) void stale.close().catch(() => {});
}
function load(): void {
if (loaded || typeof window === "undefined") return;
loaded = true;
try {
const volume = Number(localStorage.getItem(STORE_VOLUME) ?? NaN);
state = {
enabled: localStorage.getItem(STORE_ENABLED) === "1",
volume: Number.isFinite(volume) ? Math.min(1, Math.max(0, volume)) : SERVER_STATE.volume,
};
} catch {
// Storage is blocked (private mode, strict settings). Sound stays off unless turned on this visit.
}
}
function update(next: State): void {
state = next;
try {
localStorage.setItem(STORE_ENABLED, next.enabled ? "1" : "0");
localStorage.setItem(STORE_VOLUME, String(next.volume));
} catch {
// Not saved. The choice still holds for this visit.
}
for (const listener of listeners) listener();
}
function audio(): AudioContext | null {
if (ctx) return ctx;
if (typeof window === "undefined") return null;
const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
if (!Ctor) return null;
const context = new Ctor();
ctx = context;
master = createOutput(context, state.volume).input;
// A hidden page releases the audio device; the next sound wakes it.
document.addEventListener("visibilitychange", () => {
if (document.hidden && ctx === context) {
cancelIdle();
lastWallMs = 0;
void context.suspend().catch(() => {});
}
});
return context;
}
function start(name: SoundName, level: number): void {
if (!ctx || !master) return;
const context = ctx;
cancelIdle();
lastWallMs = performance.now();
lastAudioTime = context.currentTime;
// Small random changes keep a repeated sound from fatiguing: clicks move more, pitched sounds stay in tune.
const spread = SPEC[name].kind === "micro" ? 0.04 : 0.008;
sounding += 1;
renderLayers(context, master, SOUNDS[name], context.currentTime, {
pitch: 1 + (Math.random() * 2 - 1) * spread,
level: level * 10 ** ((Math.random() * 2 - 1) / 20),
onEnd: () => {
sounding = Math.max(0, sounding - 1);
if (sounding === 0 && ctx === context) scheduleIdle(context);
},
});
}
/** Play a sound, if the visitor has sound on. Safe to call anywhere, any number of times. */
export function play(name: SoundName): void {
load();
if (!state.enabled) return;
if (typeof document === "undefined" || document.hidden) return;
// Browsers block audio until the page has been clicked or typed in. Do not even create a context before that.
if (navigator.userActivation && !navigator.userActivation.hasBeenActive) return;
const now = performance.now();
const level = admit(name, now - (lastPlayed[name] ?? -Infinity), sounding);
if (!level) return;
cancelIdle();
let context = audio();
if (!context) return;
// Recover from a closed or stopped-clock AudioContext (iOS Safari after device lock/backgrounding).
if (context.state === "closed" || (context.state === "running" && lastWallMs > 0 && isClockStalled(now - lastWallMs, context.currentTime - lastAudioTime))) {
resetContext();
context = audio();
if (!context) return;
}
lastPlayed[name] = now;
if (context.state !== "running") {
lastWallMs = 0;
// Keep only the latest request, and drop it if waking the audio device takes too long.
pending = { name, at: now, level };
const waking = context;
waking
.resume()
.then(() => {
const cue = pending;
pending = null;
if (cue && state.enabled && ctx === waking && performance.now() - cue.at < STALE_MS) start(cue.name, cue.level);
})
.catch(() => {
if (ctx === waking) resetContext();
});
return;
}
start(name, level);
}
export function isSoundEnabled(): boolean {
load();
return state.enabled;
}
/** Turn sound on or off. Call it from a click or key handler: turning it on is what unlocks audio. */
export function setSoundEnabled(on: boolean): void {
load();
if (on === state.enabled) return;
update({ ...state, enabled: on });
if (on) {
if (master && ctx) {
master.gain.cancelScheduledValues(ctx.currentTime);
master.gain.setValueAtTime(masterGain(state.volume), ctx.currentTime);
}
play("toggleOn");
} else if (ctx && master) {
// Fade out whatever is ringing, then release the audio device.
cancelIdle();
lastWallMs = 0;
const context = ctx;
master.gain.setTargetAtTime(0, context.currentTime, 0.005);
setTimeout(() => {
if (!state.enabled && ctx === context) void context.suspend().catch(() => {});
}, 60);
}
}
/** Set the volume from 0 to 1. Anything else is ignored. */
export function setVolume(volume: number): void {
load();
if (!Number.isFinite(volume)) return;
const next = Math.min(1, Math.max(0, volume));
update({ ...state, volume: next });
if (ctx && master && state.enabled) master.gain.setTargetAtTime(masterGain(next), ctx.currentTime, 0.015);
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function snapshot(): State {
load();
return state;
}
/** React hook for a sound switch or volume control. */
export function useSound() {
const current = useSyncExternalStore(subscribe, snapshot, () => SERVER_STATE);
return { ...current, play, setEnabled: setSoundEnabled, setVolume };
}Files and dependencies
- Adds
lib/thrum-sound.ts- Packages
- None
- Brings along
- Nothing
Changelog
- 1.1.0 · 2026-12-03Redesigned palette: one timbre, levelled to loudness targets, success, warn and error ranked. New lift and drop. Softer repeats, a voice cap and a limiter.
- 1.0.0 · 2026-12-02First release.