Preview
"use client";
import { SoundProvider, successSound, tapSound, useSound } from "@/lib/sounds";
function SaveButton() {
const tap = useSound(tapSound);
const success = useSound(successSound);
return (
<button
type="button"
onPointerDown={() => tap()}
onClick={() => window.setTimeout(() => success(), 400)}
className="inline-flex h-9 items-center rounded-full border border-border bg-card px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted"
>
Save changes
</button>
);
}
export function SoundKitUsage() {
// One provider sets the volume for every sound, and enabled={false} mutes them.
return (
<SoundProvider volume={0.8}>
<SaveButton />
</SoundProvider>
);
}
// beui.dev/sounds/sound-kit
// Every beUI sound in one import. Install single sounds to ship only what you use.
export { SoundProvider, useSound, useSoundSettings } from "@/lib/sound";
export { bellSound } from "./bell";
export { bubbleSound } from "./bubble";
export { burstSound } from "./burst";
export { buzzSound } from "./buzz";
export { cameraSound } from "./camera";
export { checkSound } from "./check";
export { chimeSound } from "./chime";
export { closeSound } from "./close";
export { coinSound } from "./coin";
export { collapseSound } from "./collapse";
export { connectSound } from "./connect";
export { copySound } from "./copy";
export { deleteSound } from "./delete";
export { disconnectSound } from "./disconnect";
export { dismissSound } from "./dismiss";
export { dockSound } from "./dock";
export { dropSound } from "./drop";
export * from "./engine";
export { errorSound } from "./error";
export { expandSound } from "./expand";
export { heartSound } from "./heart";
export { liftSound } from "./lift";
export { lockSound } from "./lock";
export { navigateSound } from "./navigate";
export { notifySound } from "./notify";
export { openSound } from "./open";
export { pingSound } from "./ping";
export { popSound } from "./pop";
export { pressSound } from "./press";
export { receiveSound } from "./receive";
export { refreshSound } from "./refresh";
export { revealSound } from "./reveal";
export { selectSound } from "./select";
export { sendSound } from "./send";
export { shutterSound } from "./shutter";
export { snapSound } from "./snap";
export { starSound } from "./star";
export { successSound } from "./success";
export { swipeSound } from "./swipe";
export { switchSound } from "./switch";
export { tapSound } from "./tap";
export { tickSound } from "./tick";
export { timerSound } from "./timer";
export { toggleOffSound, toggleOnSound } from "./toggle";
export { trashSound } from "./trash";
export { typeSound } from "./type";
export { unlockSound } from "./unlock";
export { warningSound } from "./warning";
export { whisperSound } from "./whisper";
Add it with the shadcn CLI, or copy the source manually.
$ bunx --bun shadcn add @beui/sound-kitsound-kitsound-kit
Needs beUI's theme tokens once: paste the theme CSS, or with shadcn run
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx motion tailwind-mergeAdd util files
TSXlib/sounds/index.ts
// beui.dev/sounds/sound-kit
// Every beUI sound in one import. Install single sounds to ship only what you use.
export { SoundProvider, useSound, useSoundSettings } from "@/lib/sound";
export { bellSound } from "./bell";
export { bubbleSound } from "./bubble";
export { burstSound } from "./burst";
export { buzzSound } from "./buzz";
export { cameraSound } from "./camera";
export { checkSound } from "./check";
export { chimeSound } from "./chime";
export { closeSound } from "./close";
export { coinSound } from "./coin";
export { collapseSound } from "./collapse";
export { connectSound } from "./connect";
export { copySound } from "./copy";
export { deleteSound } from "./delete";
export { disconnectSound } from "./disconnect";
export { dismissSound } from "./dismiss";
export { dockSound } from "./dock";
export { dropSound } from "./drop";
export * from "./engine";
export { errorSound } from "./error";
export { expandSound } from "./expand";
export { heartSound } from "./heart";
export { liftSound } from "./lift";
export { lockSound } from "./lock";
export { navigateSound } from "./navigate";
export { notifySound } from "./notify";
export { openSound } from "./open";
export { pingSound } from "./ping";
export { popSound } from "./pop";
export { pressSound } from "./press";
export { receiveSound } from "./receive";
export { refreshSound } from "./refresh";
export { revealSound } from "./reveal";
export { selectSound } from "./select";
export { sendSound } from "./send";
export { shutterSound } from "./shutter";
export { snapSound } from "./snap";
export { starSound } from "./star";
export { successSound } from "./success";
export { swipeSound } from "./swipe";
export { switchSound } from "./switch";
export { tapSound } from "./tap";
export { tickSound } from "./tick";
export { timerSound } from "./timer";
export { toggleOffSound, toggleOnSound } from "./toggle";
export { trashSound } from "./trash";
export { typeSound } from "./type";
export { unlockSound } from "./unlock";
export { warningSound } from "./warning";
export { whisperSound } from "./whisper";
TSXlib/sounds/bell.ts
import { defineSound } from "./engine";
/** A resonant brass bell chime with rich natural partials, for alarms, timers and reminders. */
export const bellSound = defineSound({
name: "Bell",
duration: 0.5,
room: 0.32,
build: (v) => {
v.click({ freq: 3800, q: 1.4, decay: 0.003, gain: 0.18 });
v.strike({ freq: 659.25, material: "bell", bend: 1.003, decay: 0.45, gain: 0.5 });
v.tone({ freq: 1318.5, decay: 0.3, gain: 0.25 });
v.tone({ freq: 1977.75, decay: 0.18, gain: 0.12 });
},
});
TSXlib/sounds/bubble.ts
import { defineSound } from "./engine";
/** A rounded liquid droplet pop, for incoming chat bubbles, reactions and comments. */
export const bubbleSound = defineSound({
name: "Bubble",
duration: 0.07,
vary: 0.04,
room: 0.1,
build: (v) => {
v.click({ freq: 1600, q: 1.2, decay: 0.003, gain: 0.25 });
v.tone({ freq: 420, to: 1650, glide: 0.045, decay: 0.055, gain: 0.65 });
},
});
TSXlib/sounds/burst.ts
import { defineSound } from "./engine";
/** A celebratory triple-pop sparkle, for rewards, confetti celebrations and level-ups. */
export const burstSound = defineSound({
name: "Burst",
duration: 0.28,
room: 0.25,
build: (v) => {
for (const [at, freq, gain] of [
[0.0, 750, 0.4],
[0.035, 1150, 0.45],
[0.07, 1650, 0.5],
] as const) {
v.click({ freq: 3500, q: 1.5, at, decay: 0.003, gain: 0.18 });
v.strike({ freq, material: "mallet", at, decay: 0.14, gain });
}
},
});
TSXlib/sounds/buzz.ts
import { defineSound } from "./engine";
/** A short low haptic buzz, for rejected input, validation errors or boundary collisions. */
export const buzzSound = defineSound({
name: "Buzz",
duration: 0.09,
room: 0.05,
build: (v) => {
v.tone({ type: "sawtooth", freq: 125, attack: 0.004, decay: 0.075, gain: 0.35 });
v.strike({ freq: 95, material: "wood", decay: 0.07, gain: 0.4 });
},
});
TSXlib/sounds/camera.ts
import { defineSound } from "./engine";
/** A two-stroke camera shutter: an initial mirror-flip click and a second curtain strike. */
export const cameraSound = defineSound({
name: "Camera",
duration: 0.12,
vary: 0.03,
room: 0.15,
build: (v) => {
v.click({ freq: 2800, q: 1.4, decay: 0.005, gain: 0.5 });
v.strike({ freq: 320, material: "plastic", decay: 0.02, gain: 0.35 });
v.click({ freq: 1600, q: 1.2, at: 0.038, decay: 0.008, gain: 0.65 });
v.strike({ freq: 850, material: "metal", at: 0.038, decay: 0.045, gain: 0.45 });
},
});
TSXlib/sounds/check.ts
import { defineSound } from "./engine";
/** A crisp tactile stroke and warm upward acoustic knock, for checking off a task. */
export const checkSound = defineSound({
name: "Check",
duration: 0.12,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 3200, q: 1.6, decay: 0.004, gain: 0.45 });
v.strike({ freq: 520, material: "wood", decay: 0.04, gain: 0.5 });
v.click({ freq: 4800, q: 1.8, at: 0.04, decay: 0.003, gain: 0.4 });
v.strike({ freq: 980, material: "mallet", at: 0.04, decay: 0.06, gain: 0.55 });
},
});
TSXlib/sounds/chime.ts
import { defineSound } from "./engine";
/** A three-note ascending arpeggio on tuned bells, for milestones and completions. */
export const chimeSound = defineSound({
name: "Chime",
duration: 0.4,
room: 0.3,
build: (v) => {
for (const [at, freq] of [
[0.0, 880],
[0.035, 1108.7],
[0.07, 1318.5],
] as const) {
v.click({ freq: 4500, q: 1.2, at, decay: 0.003, gain: 0.15 });
v.strike({ freq, material: "bell", at, decay: 0.32, gain: 0.4 });
}
},
});
TSXlib/sounds/close.ts
import { defineSound } from "./engine";
/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */
export const closeSound = defineSound({
name: "Close",
duration: 0.16,
room: 0.18,
build: (v) => {
v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });
v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });
v.strike({ freq: 260, material: "wood", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });
},
});
TSXlib/sounds/coin.ts
import { defineSound } from "./engine";
/** A bright metallic coin chime with a high contact ping and long ringing overtone. */
export const coinSound = defineSound({
name: "Coin",
duration: 0.45,
vary: 0.02,
room: 0.28,
build: (v) => {
v.click({ freq: 4800, q: 2.5, decay: 0.003, gain: 0.35 });
v.strike({ freq: 2800, material: "bell", decay: 0.38, gain: 0.5 });
v.tone({ freq: 3400, decay: 0.28, gain: 0.35 });
},
});
TSXlib/sounds/collapse.ts
import { defineSound } from "./engine";
/** An inward folding tone settling into a soft tap, for collapsing panels and closing drawers. */
export const collapseSound = defineSound({
name: "Collapse",
duration: 0.13,
room: 0.14,
build: (v) => {
v.noise({ filter: "lowpass", freq: 1200, to: 350, attack: 0.008, decay: 0.09, gain: 0.4 });
v.tone({ freq: 520, to: 200, decay: 0.08, gain: 0.28 });
v.click({ freq: 1400, q: 1.2, at: 0.065, decay: 0.005, gain: 0.25 });
v.strike({ freq: 220, material: "wood", at: 0.065, decay: 0.04, gain: 0.35 });
},
});
TSXlib/sounds/connect.ts
import { defineSound } from "./engine";
/** A positive two-step connection chord, for connecting integrations, wallets and devices. */
export const connectSound = defineSound({
name: "Connect",
duration: 0.25,
room: 0.18,
build: (v) => {
v.click({ freq: 2200, q: 1.5, decay: 0.004, gain: 0.3 });
v.tone({ freq: 440, attack: 0.005, decay: 0.08, gain: 0.4 });
v.click({ freq: 3600, q: 1.8, at: 0.06, decay: 0.003, gain: 0.35 });
v.strike({ freq: 880, material: "metal", at: 0.06, decay: 0.16, gain: 0.5 });
},
});
TSXlib/sounds/copy.ts
import { defineSound } from "./engine";
/** Two quick rising glass ticks, like a small duplicate, for copying to the clipboard. */
export const copySound = defineSound({
name: "Copy",
duration: 0.1,
room: 0.1,
build: (v) => {
v.click({ freq: 4200, q: 2, decay: 0.003, gain: 0.3 });
v.strike({ freq: 1900, material: "glass", decay: 0.03, gain: 0.4 });
v.click({ freq: 5000, q: 2, at: 0.055, decay: 0.003, gain: 0.3 });
v.strike({ freq: 2500, material: "glass", at: 0.055, decay: 0.035, gain: 0.4 });
},
});
TSXlib/sounds/delete.ts
import { defineSound } from "./engine";
/** A short paper crumple that drops away, for removing or trashing an item. */
export const deleteSound = defineSound({
name: "Delete",
duration: 0.2,
room: 0.15,
build: (v) => {
// Crackles at random moments, each a little lower and quieter, so every
// crumple is different.
for (let i = 0; i < 7; i++) {
const at = i * 0.016 + Math.random() * 0.012;
v.click({ freq: 3000 - i * 300, q: 1.2, at, decay: 0.006 + Math.random() * 0.006, gain: 0.7 - i * 0.07 });
}
v.noise({ filter: "lowpass", freq: 2200, to: 300, q: 0.7, attack: 0.005, decay: 0.14, gain: 0.5 });
v.tone({ freq: 240, to: 110, attack: 0.004, decay: 0.12, gain: 0.35 });
},
});
TSXlib/sounds/disconnect.ts
import { defineSound } from "./engine";
/** A gentle downward release pop, for unlinking accounts or disconnecting devices. */
export const disconnectSound = defineSound({
name: "Disconnect",
duration: 0.18,
room: 0.14,
build: (v) => {
v.click({ freq: 3200, q: 1.4, decay: 0.004, gain: 0.35 });
v.strike({ freq: 660, material: "plastic", decay: 0.05, gain: 0.45 });
v.click({ freq: 1800, q: 1.2, at: 0.05, decay: 0.005, gain: 0.3 });
v.strike({ freq: 330, material: "wood", at: 0.05, decay: 0.08, gain: 0.5 });
},
});
TSXlib/sounds/dismiss.ts
import { defineSound } from "./engine";
/** A quick airy flick that drops away, for dismissing toasts and notifications. */
export const dismissSound = defineSound({
name: "Dismiss",
duration: 0.14,
room: 0.1,
build: (v) => {
v.noise({ filter: "bandpass", freq: 2200, to: 500, q: 0.9, decay: 0.09, gain: 0.5 });
v.tone({ freq: 620, to: 180, decay: 0.08, gain: 0.3 });
},
});
TSXlib/sounds/dock.ts
import { defineSound } from "./engine";
/** A cushioned magnetic dock thump, for pinning side panels and minimizing windows. */
export const dockSound = defineSound({
name: "Dock",
duration: 0.11,
room: 0.1,
build: (v) => {
v.click({ freq: 2200, q: 1.2, decay: 0.004, gain: 0.35 });
v.strike({ freq: 210, material: "wood", bend: 1.3, decay: 0.05, gain: 0.65 });
v.strike({ freq: 950, material: "metal", decay: 0.03, gain: 0.35 });
},
});
TSXlib/sounds/drop.ts
import { defineSound } from "./engine";
/** A soft thud with a small bounce, like an item settling on a desk, for dropping a dragged item into place. */
export const dropSound = defineSound({
name: "Drop",
duration: 0.14,
room: 0.12,
build: (v) => {
v.click({ freq: 1500, q: 1, decay: 0.005, gain: 0.18 });
v.noise({ filter: "lowpass", freq: 700, attack: 0.001, decay: 0.03, gain: 0.35 });
v.strike({ freq: 140, material: "wood", bend: 1.4, decay: 0.09, gain: 0.9 });
v.click({ freq: 1500, q: 1, at: 0.075, decay: 0.004, gain: 0.07 });
v.strike({ freq: 150, material: "wood", bend: 1.3, at: 0.075, decay: 0.05, gain: 0.3 });
},
});
TSXlib/sounds/engine.ts
import { audioOutput, getAudioContext } from "@/lib/audio-context";
// Every beUI sound is a short recipe played with Web Audio the moment it is
// asked for. Nothing is downloaded. Recipes are built the way a real tap
// sounds: a contact click (a millisecond of filtered noise), a body that
// rings at a few inharmonic partials of a material and settles in pitch, and
// a little of a small room behind it.
/** Options for one play of a sound. */
export interface PlayOptions {
/** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */
volume?: number;
/** Pitch multiplier; 1 is the designed pitch. */
pitch?: number;
}
/** Where a sound renders: the live context, or an offline one for drawing. */
export interface SoundTarget {
context: BaseAudioContext;
destination: AudioNode;
/** Start time on the context clock, in seconds. */
when: number;
volume: number;
pitch: number;
}
/** A plain oscillator with an attack, a decay and an optional glide. */
export interface ToneSpec {
type?: OscillatorType;
/** Start frequency in Hz. */
freq: number;
/** End frequency in Hz; glides from `freq` over `glide`. */
to?: number;
/** Glide time in seconds; defaults to the attack plus decay. */
glide?: number;
/** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** A burst of filtered white noise. */
export interface NoiseSpec {
filter?: BiquadFilterType;
/** Filter frequency in Hz. */
freq: number;
/** End filter frequency in Hz; sweeps from `freq` over the decay. */
to?: number;
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Fade-in time in seconds. */
attack?: number;
/** Time to fade to silence after the attack, in seconds. */
decay: number;
gain: number;
}
/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */
export interface ClickSpec {
/** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */
freq: number;
/** Band width; higher is narrower and more tonal. */
q?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time to fade to silence, in seconds. */
decay?: number;
gain: number;
}
/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */
export interface Material {
partials: readonly (readonly [ratio: number, level: number])[];
/** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */
damping: number;
}
// Partial ratios follow the modes of small struck objects: a free bar for
// wood and metal, a cup for glass, a tuned bar for the mallet.
export const MATERIALS = {
wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },
plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },
glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },
metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },
mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },
bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },
} satisfies Record<string, Material>;
/** A struck object: one partial per mode of its material, each with its own decay. */
export interface StrikeSpec {
/** Fundamental in Hz. */
freq: number;
/** A name from `MATERIALS` or your own partials. Default: "plastic". */
material?: keyof typeof MATERIALS | Material;
/** Starts this many times higher and settles in about 15 ms. Default: 1.01. */
bend?: number;
/** Delay from the sound's start, in seconds. */
at?: number;
/** Time for the fundamental to fade to silence, in seconds. */
decay: number;
gain: number;
}
export interface Voice {
tone(spec: ToneSpec): void;
noise(spec: NoiseSpec): void;
click(spec: ClickSpec): void;
strike(spec: StrikeSpec): void;
}
export interface Sound {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Plays the sound now. Silent during SSR and while sounds are muted. */
play(options?: PlayOptions): void;
/** Schedules the sound on any context; `play` uses the live one. */
render(target: SoundTarget): void;
}
export interface SoundRecipe {
/** Display name, like "Tap". */
name: string;
/** Length in seconds; the room tail rings a little past it. */
duration: number;
/** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */
vary?: number;
/** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */
room?: number;
/** Adds the sound's layers to the voice on each play. */
build: (voice: Voice) => void;
}
// Keeps a sum of voices well under clipping at volume 1.
const MASTER_GAIN = 0.16;
const SILENT = 0.0001;
// Time a strike or bend takes to settle onto its pitch.
const SETTLE = 0.015;
const noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
/** One second of white noise per context, shared by every noise voice. */
export function noiseBuffer(context: BaseAudioContext) {
let buffer = noiseBuffers.get(context);
if (!buffer) {
buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
noiseBuffers.set(context, buffer);
}
return buffer;
}
// A small, soft room: 8 early reflections, then a diffuse tail that falls
// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls
// absorb highs first. Generated once per context.
const ROOM_LENGTH = 0.3;
// The convolver's equal-power normalization leaves the room about 15 dB
// under the dry sound; this brings `room: 0.12` to a tail heard only as space.
const ROOM_GAIN = 6;
const roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();
function roomBuffer(context: BaseAudioContext) {
let buffer = roomBuffers.get(context);
if (!buffer) {
const rate = context.sampleRate;
const length = Math.ceil(ROOM_LENGTH * rate);
buffer = context.createBuffer(2, length, rate);
for (let channel = 0; channel < 2; channel++) {
const data = buffer.getChannelData(channel);
let smooth = 0;
for (let i = Math.floor(0.004 * rate); i < length; i++) {
const t = i / rate;
// One-pole low-pass whose cutoff closes over the tail.
const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;
smooth += brightness * (Math.random() * 2 - 1 - smooth);
data[i] = smooth * Math.exp(-t / 0.043);
}
for (let r = 0; r < 8; r++) {
const at = Math.floor((0.005 + Math.random() * 0.022) * rate);
data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);
}
}
roomBuffers.set(context, buffer);
}
return buffer;
}
// One convolver per output node, shared by every play: building one is the
// expensive part, sending to it is cheap.
const rooms = new WeakMap<AudioNode, ConvolverNode>();
function roomFor(context: BaseAudioContext, destination: AudioNode) {
let room = rooms.get(destination);
if (!room) {
room = context.createConvolver();
room.buffer = roomBuffer(context);
room.connect(destination);
rooms.set(destination, room);
}
return room;
}
/** A linear attack to `peak`, then an exponential fall to silence. */
function envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {
param.setValueAtTime(0, start);
param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);
param.exponentialRampToValueAtTime(SILENT, start + attack + decay);
}
function voiceFor(target: SoundTarget, output: AudioNode): Voice {
const { context, when, pitch } = target;
// Partials above this only add hiss on small speakers, or alias near Nyquist.
const ceiling = Math.min(12000, context.sampleRate * 0.45);
const tone: Voice["tone"] = ({ type = "sine", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const osc = context.createOscillator();
const amp = context.createGain();
osc.type = type;
const base = freq * pitch;
osc.frequency.setValueAtTime(base * (bend ?? 1), start);
if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);
if (to !== undefined) {
osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));
}
envelope(amp.gain, start, attack, decay, gain);
osc.connect(amp).connect(output);
osc.start(start);
osc.stop(start + attack + decay + 0.02);
};
const noise: Voice["noise"] = ({ filter = "bandpass", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {
const start = when + at;
const source = context.createBufferSource();
const shape = context.createBiquadFilter();
const amp = context.createGain();
source.buffer = noiseBuffer(context);
shape.type = filter;
shape.Q.value = q;
shape.frequency.setValueAtTime(freq * pitch, start);
if (to !== undefined) {
shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);
}
envelope(amp.gain, start, attack, decay, gain);
source.connect(shape).connect(amp).connect(output);
// A random offset into the buffer keeps each burst a little different.
source.start(start, Math.random() * 0.5);
source.stop(start + attack + decay + 0.02);
};
return {
tone,
noise,
click({ freq, q = 2, at = 0, decay = 0.005, gain }) {
// A little spread on the band, so no two contacts are identical.
noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });
},
strike({ freq, material = "plastic", bend = 1.01, at = 0, decay, gain }) {
const { partials, damping } = typeof material === "string" ? MATERIALS[material] : material;
for (const [ratio, level] of partials) {
if (freq * ratio * pitch * bend > ceiling) continue;
tone({
// Real objects are never perfectly tuned; a hair of detune per partial.
freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),
bend,
at,
attack: 0.001,
decay: decay / ratio ** damping,
gain: gain * level,
});
}
},
};
}
/** Turns a recipe into a playable sound. */
export function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {
const render = (target: SoundTarget) => {
const { context, destination } = target;
const output = context.createGain();
output.gain.value = MASTER_GAIN * target.volume;
output.connect(destination);
if (room > 0) {
const send = context.createGain();
send.gain.value = room * ROOM_GAIN;
output.connect(send).connect(roomFor(context, destination));
}
build(voiceFor(target, output));
};
return {
name,
duration,
render,
play({ volume = 1, pitch = 1 } = {}) {
const context = getAudioContext();
if (!context || volume <= 0) return;
const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;
render({
context,
// The page-wide volume is applied there.
destination: audioOutput(context),
when: context.currentTime + 0.005,
volume,
pitch: pitch * spread,
});
},
};
}
TSXlib/sounds/error.ts
import { defineSound } from "./engine";
/** Two dull wooden knocks falling, with a soft beat in each, for a failed action. */
export const errorSound = defineSound({
name: "Error",
duration: 0.35,
room: 0.15,
build: (v) => {
for (const [at, freq, decay] of [
[0, 330, 0.12],
[0.1, 262, 0.2],
] as const) {
v.click({ freq: 1200, q: 1, at, decay: 0.006, gain: 0.28 });
v.strike({ freq, material: "wood", bend: 1.08, at, decay, gain: 0.5 });
// A second body a hair flat beats against the first: the old buzz, softened.
v.tone({ freq: freq * 1.012, at, decay: decay * 0.8, gain: 0.18 });
v.tone({ freq: freq / 2, bend: 1.2, at, decay: decay * 0.5, gain: 0.22 });
}
},
});
TSXlib/sounds/expand.ts
import { defineSound } from "./engine";
/** A gentle blooming whoosh opening outward, for expanding accordions, cards and sheets. */
export const expandSound = defineSound({
name: "Expand",
duration: 0.15,
room: 0.15,
build: (v) => {
v.noise({ filter: "lowpass", freq: 400, to: 1400, attack: 0.02, decay: 0.11, gain: 0.4 });
v.tone({ freq: 220, to: 520, attack: 0.015, decay: 0.12, gain: 0.3 });
},
});
TSXlib/sounds/heart.ts
import { defineSound } from "./engine";
/** A warm two-beat acoustic pulse, for likes, favorites and bookmark interactions. */
export const heartSound = defineSound({
name: "Heart",
duration: 0.3,
room: 0.18,
build: (v) => {
v.click({ freq: 600, q: 0.8, decay: 0.008, gain: 0.3 });
v.strike({ freq: 72, material: "wood", decay: 0.08, gain: 0.75 });
v.click({ freq: 700, q: 0.8, at: 0.08, decay: 0.008, gain: 0.3 });
v.strike({ freq: 88, material: "wood", at: 0.08, decay: 0.1, gain: 0.7 });
},
});
TSXlib/sounds/lift.ts
import { defineSound } from "./engine";
/** A soft lift click with rising resonance, for picking up or starting to drag an item. */
export const liftSound = defineSound({
name: "Lift",
duration: 0.1,
vary: 0.03,
room: 0.08,
build: (v) => {
v.click({ freq: 2400, q: 1.2, decay: 0.004, gain: 0.35 });
v.strike({ freq: 160, material: "wood", bend: 1.25, decay: 0.05, gain: 0.5 });
v.tone({ freq: 180, to: 340, attack: 0.005, decay: 0.06, gain: 0.25 });
},
});
TSXlib/sounds/lock.ts
import { defineSound } from "./engine";
/** A solid mechanical latch engaging with a tumbler click and deep lock body thump. */
export const lockSound = defineSound({
name: "Lock",
duration: 0.12,
room: 0.14,
build: (v) => {
v.click({ freq: 3400, q: 1.8, decay: 0.004, gain: 0.45 });
v.strike({ freq: 1950, material: "metal", decay: 0.03, gain: 0.5 });
v.strike({ freq: 160, material: "wood", bend: 1.3, decay: 0.06, gain: 0.7 });
},
});
TSXlib/sounds/navigate.ts
import { defineSound } from "./engine";
/** A quick airy slide, like a page passing under a hand, for moving between pages, steps or slides. */
export const navigateSound = defineSound({
name: "Navigate",
duration: 0.1,
vary: 0.03,
room: 0.15,
build: (v) => {
v.noise({ freq: 1000, to: 3600, q: 0.7, attack: 0.025, decay: 0.06, gain: 0.55 });
v.noise({ freq: 5500, q: 1, attack: 0.02, decay: 0.04, gain: 0.04 });
v.click({ freq: 2400, q: 1.2, at: 0.055, decay: 0.004, gain: 0.08 });
},
});
TSXlib/sounds/notify.ts
import { defineSound } from "./engine";
/** A small struck bell with a slow shimmer, for a new message or toast. */
export const notifySound = defineSound({
name: "Notify",
duration: 0.55,
room: 0.3,
build: (v) => {
v.click({ freq: 5000, q: 1.5, decay: 0.003, gain: 0.16 });
v.strike({ freq: 1568, material: "bell", bend: 1.004, decay: 0.48, gain: 0.42 });
// A twin 5 Hz sharp beats against it: the shimmer of a real bell.
v.tone({ freq: 1573, decay: 0.45, gain: 0.2 });
},
});
TSXlib/sounds/open.ts
import { defineSound } from "./engine";
/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */
export const openSound = defineSound({
name: "Open",
duration: 0.2,
room: 0.2,
build: (v) => {
v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });
v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });
v.strike({ freq: 1320, material: "glass", at: 0.05, decay: 0.07, gain: 0.12 });
},
});
TSXlib/sounds/ping.ts
import { defineSound } from "./engine";
/** A pure high crystalline bell ring, for mentions, badges and live activity alerts. */
export const pingSound = defineSound({
name: "Ping",
duration: 0.35,
room: 0.25,
build: (v) => {
v.click({ freq: 6000, q: 2, decay: 0.002, gain: 0.2 });
v.strike({ freq: 2349, material: "bell", decay: 0.3, gain: 0.45 });
v.tone({ freq: 4698, decay: 0.15, gain: 0.15 });
},
});
TSXlib/sounds/pop.ts
import { defineSound } from "./engine";
/** A rounded bubbly pop sweeping quickly upward, for chips, badges and notifications. */
export const popSound = defineSound({
name: "Pop",
duration: 0.06,
vary: 0.04,
room: 0.08,
build: (v) => {
v.click({ freq: 1800, q: 1, decay: 0.003, gain: 0.3 });
v.tone({ freq: 220, to: 750, glide: 0.035, decay: 0.04, gain: 0.65 });
},
});
TSXlib/sounds/press.ts
import { defineSound } from "./engine";
/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */
export const pressSound = defineSound({
name: "Press",
duration: 0.1,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });
v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });
v.strike({ freq: 150, material: "wood", bend: 1.5, decay: 0.07, gain: 0.75 });
v.strike({ freq: 1250, material: "plastic", decay: 0.022, gain: 0.14 });
},
});
TSXlib/sounds/receive.ts
import { defineSound } from "./engine";
/** Two soft descending mallet notes, for incoming chat messages and replies. */
export const receiveSound = defineSound({
name: "Receive",
duration: 0.32,
room: 0.22,
build: (v) => {
v.click({ freq: 4000, q: 1.2, decay: 0.003, gain: 0.18 });
v.strike({ freq: 1318.5, material: "mallet", decay: 0.18, gain: 0.45 });
v.click({ freq: 3500, q: 1.2, at: 0.065, decay: 0.003, gain: 0.18 });
v.strike({ freq: 880, material: "mallet", at: 0.065, decay: 0.24, gain: 0.5 });
},
});
TSXlib/sounds/refresh.ts
import { defineSound } from "./engine";
/** A springy upward swirl with a soft release chime, for pull-to-refresh and feed updates. */
export const refreshSound = defineSound({
name: "Refresh",
duration: 0.28,
room: 0.2,
build: (v) => {
v.tone({ freq: 440, to: 880, attack: 0.005, decay: 0.08, gain: 0.35 });
v.click({ freq: 3600, q: 1.5, at: 0.09, decay: 0.003, gain: 0.2 });
v.strike({ freq: 1318.5, material: "bell", at: 0.09, decay: 0.18, gain: 0.45 });
},
});
TSXlib/sounds/reveal.ts
import { defineSound } from "./engine";
/** A soft upward glass flourish, for revealing hidden content, passwords and secret keys. */
export const revealSound = defineSound({
name: "Reveal",
duration: 0.22,
room: 0.2,
build: (v) => {
v.click({ freq: 4200, q: 1.8, decay: 0.003, gain: 0.25 });
v.tone({ freq: 587.3, to: 1174.6, glide: 0.08, attack: 0.01, decay: 0.14, gain: 0.45 });
v.strike({ freq: 1760, material: "glass", at: 0.06, decay: 0.14, gain: 0.4 });
},
});
TSXlib/sounds/select.ts
import { defineSound } from "./engine";
/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */
export const selectSound = defineSound({
name: "Select",
duration: 0.05,
room: 0.08,
build: (v) => {
v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });
v.strike({ freq: 1700, material: "metal", decay: 0.028, gain: 0.3 });
v.strike({ freq: 520, material: "wood", bend: 1.15, decay: 0.012, gain: 0.25 });
},
});
TSXlib/sounds/send.ts
import { defineSound } from "./engine";
/** An upward airy whoosh with a clean release tap, for sending messages and emails. */
export const sendSound = defineSound({
name: "Send",
duration: 0.18,
room: 0.15,
build: (v) => {
v.noise({ filter: "bandpass", freq: 800, to: 2800, q: 1, decay: 0.12, gain: 0.5 });
v.tone({ freq: 440, to: 1200, attack: 0.01, decay: 0.1, gain: 0.35 });
v.click({ freq: 3800, q: 1.5, at: 0.09, decay: 0.004, gain: 0.25 });
},
});
TSXlib/sounds/shutter.ts
import { defineSound } from "./engine";
/** A rapid mechanical aperture leaf snap with metallic body ring, for camera snapshots. */
export const shutterSound = defineSound({
name: "Shutter",
duration: 0.09,
vary: 0.02,
room: 0.12,
build: (v) => {
v.click({ freq: 4400, q: 2, decay: 0.003, gain: 0.55 });
v.strike({ freq: 1850, material: "metal", decay: 0.025, gain: 0.4 });
v.click({ freq: 2800, q: 1.4, at: 0.028, decay: 0.004, gain: 0.45 });
v.strike({ freq: 950, material: "metal", at: 0.028, decay: 0.04, gain: 0.45 });
},
});
TSXlib/sounds/snap.ts
import { defineSound } from "./engine";
/** A sharp mechanical latch click, for magnets, grid snapping and docking into place. */
export const snapSound = defineSound({
name: "Snap",
duration: 0.05,
vary: 0.02,
room: 0.08,
build: (v) => {
v.click({ freq: 4200, q: 2, decay: 0.003, gain: 0.55 });
v.strike({ freq: 1200, material: "plastic", decay: 0.025, gain: 0.4 });
v.strike({ freq: 320, material: "wood", bend: 1.2, decay: 0.03, gain: 0.45 });
},
});
TSXlib/sounds/star.ts
import { defineSound } from "./engine";
/** A bright crystalline sparkle chime, for starring repositories and bookmarks. */
export const starSound = defineSound({
name: "Star",
duration: 0.4,
room: 0.28,
build: (v) => {
v.click({ freq: 5200, q: 2, decay: 0.003, gain: 0.25 });
v.strike({ freq: 1760, material: "bell", decay: 0.35, gain: 0.5 });
v.strike({ freq: 2637, material: "bell", at: 0.03, decay: 0.32, gain: 0.4 });
v.tone({ freq: 3520, at: 0.03, decay: 0.2, gain: 0.2 });
},
});
TSXlib/sounds/success.ts
import { defineSound } from "./engine";
/** Two soft mallet notes on a wooden bar, rising a fifth, for a saved or completed action. */
export const successSound = defineSound({
name: "Success",
duration: 0.5,
room: 0.25,
build: (v) => {
v.click({ freq: 2500, q: 1, decay: 0.004, gain: 0.18 });
v.strike({ freq: 1047, material: "mallet", decay: 0.28, gain: 0.5 });
v.click({ freq: 2500, q: 1, at: 0.085, decay: 0.004, gain: 0.18 });
v.strike({ freq: 1568, material: "mallet", at: 0.085, decay: 0.38, gain: 0.5 });
},
});
TSXlib/sounds/swipe.ts
import { defineSound } from "./engine";
/** An airy whoosh with subtle friction contact, for gesture swipes, carousels and page turns. */
export const swipeSound = defineSound({
name: "Swipe",
duration: 0.12,
vary: 0.04,
room: 0.1,
build: (v) => {
v.noise({ filter: "bandpass", freq: 1600, to: 600, q: 0.8, decay: 0.1, gain: 0.45 });
v.tone({ freq: 380, to: 160, attack: 0.005, decay: 0.08, gain: 0.25 });
},
});
TSXlib/sounds/switch.ts
import { defineSound } from "./engine";
/** A tactile hardware rocker switch with a double micro-click, for toggle switches. */
export const switchSound = defineSound({
name: "Switch",
duration: 0.07,
vary: 0.03,
room: 0.1,
build: (v) => {
v.click({ freq: 2600, q: 1.5, decay: 0.004, gain: 0.45 });
v.strike({ freq: 720, material: "plastic", decay: 0.02, gain: 0.35 });
v.click({ freq: 3800, q: 1.8, at: 0.022, decay: 0.004, gain: 0.5 });
v.strike({ freq: 1400, material: "plastic", at: 0.022, decay: 0.03, gain: 0.4 });
},
});
TSXlib/sounds/tap.ts
import { defineSound } from "./engine";
/** A fingertip on glass: a crisp contact, a small glass ring and a soft knock under it. */
export const tapSound = defineSound({
name: "Tap",
duration: 0.08,
vary: 0.04,
room: 0.1,
build: (v) => {
v.click({ freq: 3600, q: 1.6, decay: 0.004, gain: 0.55 });
v.strike({ freq: 2150, material: "glass", decay: 0.04, gain: 0.32 });
v.strike({ freq: 210, material: "wood", bend: 1.25, decay: 0.03, gain: 0.45 });
},
});
TSXlib/sounds/tick.ts
import { defineSound } from "./engine";
/** A tiny dry metal tick, for counters, sliders, pickers and loading steps. */
export const tickSound = defineSound({
name: "Tick",
duration: 0.02,
vary: 0.02,
// Dry, so fast repeats on a slider stay separate.
room: 0,
build: (v) => {
v.click({ freq: 5000, q: 3, decay: 0.0025, gain: 0.4 });
v.strike({ freq: 3400, material: "metal", decay: 0.01, gain: 0.32 });
},
});
TSXlib/sounds/timer.ts
import { defineSound } from "./engine";
/** A dry hollow woodblock pulse, for countdown timers, metronomes and turn-counters. */
export const timerSound = defineSound({
name: "Timer",
duration: 0.06,
room: 0,
build: (v) => {
v.click({ freq: 3600, q: 2, decay: 0.003, gain: 0.5 });
v.strike({ freq: 780, material: "wood", bend: 1.15, decay: 0.03, gain: 0.65 });
},
});
TSXlib/sounds/toggle.ts
import { defineSound } from "./engine";
// A real switch clicks twice: a light pre-click as it starts to travel, then
// the snap as it lands. On goes low to high and lands on a higher body; off
// is the mirror, so the two are easy to tell apart.
/** A two-stage snap rising into place, for switching something on. */
export const toggleOnSound = defineSound({
name: "Toggle on",
duration: 0.1,
room: 0.1,
build: (v) => {
v.click({ freq: 2000, q: 1.5, decay: 0.004, gain: 0.22 });
v.click({ freq: 3800, q: 2, at: 0.024, decay: 0.005, gain: 0.5 });
v.strike({ freq: 980, material: "plastic", bend: 1.05, at: 0.024, decay: 0.045, gain: 0.5 });
v.strike({ freq: 190, material: "wood", bend: 1.3, at: 0.024, decay: 0.03, gain: 0.35 });
},
});
/** The same snap falling into place, for switching something off. */
export const toggleOffSound = defineSound({
name: "Toggle off",
duration: 0.1,
room: 0.1,
build: (v) => {
v.click({ freq: 3800, q: 2, decay: 0.004, gain: 0.22 });
v.click({ freq: 2000, q: 1.5, at: 0.024, decay: 0.005, gain: 0.5 });
v.strike({ freq: 640, material: "plastic", bend: 1.05, at: 0.024, decay: 0.045, gain: 0.5 });
v.strike({ freq: 160, material: "wood", bend: 1.3, at: 0.024, decay: 0.03, gain: 0.35 });
},
});
TSXlib/sounds/trash.ts
import { defineSound } from "./engine";
/** A hollow wooden-metallic drop with a short textured rustle, for discarding an item. */
export const trashSound = defineSound({
name: "Trash",
duration: 0.18,
room: 0.15,
build: (v) => {
v.click({ freq: 1800, q: 1, decay: 0.006, gain: 0.35 });
v.noise({ filter: "bandpass", freq: 1200, to: 400, decay: 0.08, gain: 0.4 });
v.strike({ freq: 320, material: "wood", bend: 1.3, decay: 0.09, gain: 0.6 });
v.strike({ freq: 140, material: "metal", at: 0.03, decay: 0.06, gain: 0.3 });
},
});
TSXlib/sounds/type.ts
import { defineSound } from "./engine";
/** A keystroke: the key's click, its spring, and a soft thock as it bottoms out. */
export const typeSound = defineSound({
name: "Type",
duration: 0.05,
vary: 0.08,
room: 0.06,
build: (v) => {
v.click({ freq: 3200, q: 1.2, decay: 0.007, gain: 0.55 });
v.click({ freq: 6200, q: 3, at: 0.005, decay: 0.002, gain: 0.12 });
v.strike({ freq: 330, material: "wood", bend: 1.2, at: 0.004, decay: 0.025, gain: 0.35 });
},
});
TSXlib/sounds/unlock.ts
import { defineSound } from "./engine";
/** Two quick rising metal clicks, like a mechanical tumbler releasing, for unlocking. */
export const unlockSound = defineSound({
name: "Unlock",
duration: 0.14,
room: 0.12,
build: (v) => {
v.click({ freq: 2200, q: 1.6, at: 0.01, decay: 0.004, gain: 0.4 });
v.strike({ freq: 1800, material: "metal", at: 0.01, decay: 0.025, gain: 0.35 });
v.click({ freq: 3600, q: 2, at: 0.032, decay: 0.004, gain: 0.5 });
v.strike({ freq: 2400, material: "metal", at: 0.032, decay: 0.035, gain: 0.45 });
},
});
TSXlib/sounds/warning.ts
import { defineSound } from "./engine";
/** Two even taps on a small glass block, for a heads-up that needs a look. */
export const warningSound = defineSound({
name: "Warning",
duration: 0.3,
room: 0.18,
build: (v) => {
for (const at of [0, 0.12]) {
v.click({ freq: 2200, q: 1.4, at, decay: 0.004, gain: 0.22 });
v.strike({ freq: 740, material: "glass", at, decay: 0.1, gain: 0.45 });
}
},
});
TSXlib/sounds/whisper.ts
import { defineSound } from "./engine";
/** An ultra-soft acoustic puff, for subtle hover hints, tooltips and micro-badges. */
export const whisperSound = defineSound({
name: "Whisper",
duration: 0.08,
vary: 0.03,
room: 0.06,
build: (v) => {
v.noise({ filter: "lowpass", freq: 1100, attack: 0.008, decay: 0.05, gain: 0.25 });
v.strike({ freq: 480, material: "plastic", decay: 0.025, gain: 0.2 });
},
});
TSXlib/sound.tsx
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import {
registerSoundSettings,
retainAudioContext,
type SoundSettingsEntry,
} from "@/lib/audio-context";
import type { PlayOptions, Sound } from "@/lib/sounds/engine";
export interface SoundSettings {
/** False mutes every beUI sound under the provider. */
enabled: boolean;
/** 0 to 1, scales every beUI sound. */
volume: number;
}
const SoundContext = createContext<SoundSettings & { depth: number }>({
enabled: true,
volume: 1,
depth: 0,
});
/**
* App-wide sound settings. `enabled={false}` mutes every beUI sound, from
* component `sound` props and `useSound` to the games, Wheel Picker and
* Bookshelf, and `volume` scales them all. Without a provider, sounds play at
* full volume. A nested provider overrides the one around it.
*/
export function SoundProvider({
enabled = true,
volume = 1,
children,
}: Partial<SoundSettings> & { children: ReactNode }) {
const depth = useContext(SoundContext).depth + 1;
const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);
// Module-level as well (lib/audio-context.ts), so players outside React
// and `sound.play()` obey it too.
const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });
const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);
useEffect(() => {
registration.current = registerSoundSettings(entry.current);
return () => {
registration.current?.release();
registration.current = null;
};
}, []);
useEffect(() => {
Object.assign(entry.current, { depth, enabled, volume });
registration.current?.update();
}, [depth, enabled, volume]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}
export function useSoundSettings(): SoundSettings {
return useContext(SoundContext);
}
export interface UseSoundOptions {
/** False makes `play` do nothing, for a component's `sound` prop. */
enabled?: boolean;
/** 0 to 1 for this sound, on top of the provider volume. */
volume?: number;
}
/**
* A stable `play()` for one sound. It does nothing while disabled or muted,
* and keeps the shared audio context warm only while it can play.
*/
export function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {
const settings = useSoundSettings();
const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;
// Read by the stable callback, so a caller's effects don't re-run when
// the settings change.
const latest = useRef({ on, volume, sound });
useLayoutEffect(() => {
latest.current = { on, volume, sound };
});
useEffect(() => {
if (!on) return;
return retainAudioContext();
}, [on]);
return useCallback((options?: PlayOptions) => {
const current = latest.current;
if (!current.on) return;
current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });
}, []);
}
TSXlib/audio-context.ts
// One AudioContext for every synthesized sound on the page: the sounds
// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino
// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap
// concurrent contexts, and a page can show a date made of several WheelPickers
// next to a game, so they all share this one. It is created on first use and
// closed once every player is disposed.
//
// Every player connects to `audioOutput()` rather than the context's
// destination, so the page-wide volume and mute from `SoundProvider`
// (lib/sound.tsx) reach all of them in one place.
type AudioContextCtor = typeof AudioContext;
let context: AudioContext | null = null;
let master: GainNode | null = null;
let users = 0;
/** Settings one mounted `SoundProvider` asks for. */
export interface SoundSettingsEntry {
/** Nesting depth: the deepest provider decides. */
depth: number;
enabled: boolean;
volume: number;
}
// Mounted providers in mount order. Module state, so `sound.play()` called
// outside React obeys them too. The deepest provider wins; among equals, the
// one mounted last. Effects run child first, so this can't be "whoever ran
// last".
const providers = new Set<SoundSettingsEntry>();
let allowed = true;
let volume = 1;
function applySettings() {
let chosen: SoundSettingsEntry | undefined;
for (const entry of providers) {
if (!chosen || entry.depth >= chosen.depth) chosen = entry;
}
allowed = chosen?.enabled ?? true;
volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));
if (master) master.gain.value = volume;
}
/**
* Registers a provider's settings; call `update` after changing the entry and
* the returned release function when the provider unmounts.
*/
export function registerSoundSettings(entry: SoundSettingsEntry) {
providers.add(entry);
applySettings();
return {
update: applySettings,
release() {
providers.delete(entry);
applySettings();
},
};
}
/**
* Registers a sound player. Call the returned function when the player is
* disposed; the context closes after the last one.
*/
export function retainAudioContext() {
users++;
let released = false;
return () => {
if (released) return;
released = true;
users--;
if (users === 0 && context) {
void context.close();
context = null;
master = null;
}
};
}
/**
* The shared context, created on first call and resumed if suspended. Null
* during SSR, in browsers without Web Audio, and while sounds are muted or at
* zero volume.
*/
export function getAudioContext(): AudioContext | null {
if (!allowed || volume <= 0) return null;
if (!context) {
if (typeof window === "undefined") return null;
const Ctor =
window.AudioContext ??
(window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
}
// Browsers may refuse outside a user gesture. Players call this from
// pointer and key handlers first, so a later call finds it running.
if (context.state === "suspended") void context.resume().catch(() => undefined);
return context;
}
/** The node every player connects to: the page-wide volume, then the speakers. */
export function audioOutput(ctx: AudioContext): AudioNode {
if (master?.context !== ctx) {
master = ctx.createGain();
master.gain.value = volume;
master.connect(ctx.destination);
}
return master;
}
const gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();
/**
* A player's own level, made once per context and routed into `audioOutput`.
* Players keep their mix this way without rebuilding nodes on every play, and
* a context closed and recreated gets fresh ones.
*/
export function playerGain(ctx: AudioContext, key: string, level: number): GainNode {
let byKey = gains.get(ctx);
if (!byKey) {
byKey = new Map();
gains.set(ctx, byKey);
}
let gain = byKey.get(key);
if (!gain) {
gain = ctx.createGain();
gain.gain.value = level;
gain.connect(audioOutput(ctx));
byKey.set(key, gain);
}
return gain;
}
TSXlib/utils.ts
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
TSXlib/ease.ts
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
Copy the source code
TSXcomponents/previews/sounds/sound-board.tsx
"use client";
import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { SOUND_ITEMS, type SoundItem } from "./sound-list";
import { SoundPad } from "./sound-pad";
type PadState = { pulse: number; index: number };
function isTyping(target: EventTarget | null) {
if (!(target instanceof HTMLElement)) return false;
return target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName);
}
/**
* Every sound as a pad. With `shortcuts`, each pad also plays from its key
* (1 to 0, then Q to Y) while focus isn't in a text field.
*/
export function SoundBoard({
items = SOUND_ITEMS,
shortcuts = true,
renderName,
className,
}: {
items?: SoundItem[];
shortcuts?: boolean;
/** Wraps each pad's name, for example in a link to the sound's page. */
renderName?: (item: SoundItem) => ReactNode;
className?: string;
}) {
const counts = useRef<Record<string, number>>({});
const [pads, setPads] = useState<Record<string, PadState>>({});
const play = useCallback((item: SoundItem) => {
const index = (counts.current[item.slug] ?? 0) % item.sounds.length;
item.sounds[index].play();
counts.current[item.slug] = index + 1;
setPads((current) => ({
...current,
[item.slug]: { pulse: (current[item.slug]?.pulse ?? 0) + 1, index },
}));
}, []);
useEffect(() => {
if (!shortcuts) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.repeat || event.metaKey || event.ctrlKey || event.altKey) return;
if (isTyping(event.target)) return;
const item = items.find((entry) => entry.key === event.key.toLowerCase());
if (item) play(item);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [items, play, shortcuts]);
// Columns follow the board's own width, so it fits a page or a preview stage.
return (
<div className={cn("@container", className)}>
<div className="grid grid-cols-2 gap-3 @xl:grid-cols-3 @3xl:grid-cols-4">
{items.map((item) => {
const pad = pads[item.slug];
return (
<SoundPad
key={item.slug}
name={item.name}
sound={item.sounds[pad?.index ?? 0]}
pulse={pad?.pulse ?? 0}
onPress={() => play(item)}
keyHint={shortcuts ? item.key : undefined}
nameSlot={renderName?.(item)}
/>
);
})}
</div>
</div>
);
}
TSXcomponents/previews/sounds/sound-list.ts
import { bellSound } from "@/lib/sounds/bell";
import { bubbleSound } from "@/lib/sounds/bubble";
import { burstSound } from "@/lib/sounds/burst";
import { buzzSound } from "@/lib/sounds/buzz";
import { cameraSound } from "@/lib/sounds/camera";
import { checkSound } from "@/lib/sounds/check";
import { chimeSound } from "@/lib/sounds/chime";
import { closeSound } from "@/lib/sounds/close";
import { coinSound } from "@/lib/sounds/coin";
import { collapseSound } from "@/lib/sounds/collapse";
import { connectSound } from "@/lib/sounds/connect";
import { copySound } from "@/lib/sounds/copy";
import { deleteSound } from "@/lib/sounds/delete";
import { disconnectSound } from "@/lib/sounds/disconnect";
import { dismissSound } from "@/lib/sounds/dismiss";
import { dockSound } from "@/lib/sounds/dock";
import { dropSound } from "@/lib/sounds/drop";
import type { Sound } from "@/lib/sounds/engine";
import { errorSound } from "@/lib/sounds/error";
import { expandSound } from "@/lib/sounds/expand";
import { heartSound } from "@/lib/sounds/heart";
import { liftSound } from "@/lib/sounds/lift";
import { lockSound } from "@/lib/sounds/lock";
import { navigateSound } from "@/lib/sounds/navigate";
import { notifySound } from "@/lib/sounds/notify";
import { openSound } from "@/lib/sounds/open";
import { pingSound } from "@/lib/sounds/ping";
import { popSound } from "@/lib/sounds/pop";
import { pressSound } from "@/lib/sounds/press";
import { receiveSound } from "@/lib/sounds/receive";
import { refreshSound } from "@/lib/sounds/refresh";
import { revealSound } from "@/lib/sounds/reveal";
import { selectSound } from "@/lib/sounds/select";
import { sendSound } from "@/lib/sounds/send";
import { shutterSound } from "@/lib/sounds/shutter";
import { snapSound } from "@/lib/sounds/snap";
import { starSound } from "@/lib/sounds/star";
import { successSound } from "@/lib/sounds/success";
import { swipeSound } from "@/lib/sounds/swipe";
import { switchSound } from "@/lib/sounds/switch";
import { tapSound } from "@/lib/sounds/tap";
import { tickSound } from "@/lib/sounds/tick";
import { timerSound } from "@/lib/sounds/timer";
import { toggleOffSound, toggleOnSound } from "@/lib/sounds/toggle";
import { trashSound } from "@/lib/sounds/trash";
import { typeSound } from "@/lib/sounds/type";
import { unlockSound } from "@/lib/sounds/unlock";
import { warningSound } from "@/lib/sounds/warning";
import { whisperSound } from "@/lib/sounds/whisper";
export interface SoundItem {
/** Registry slug of the sound's page. */
slug: string;
name: string;
/** Keyboard shortcut on the sound board. */
key?: string;
/** Played in turn on each press; toggle alternates on and off. */
sounds: Sound[];
}
export const SOUND_ITEMS: SoundItem[] = [
// Numbers 1 to 0
{ slug: "tap-sound", name: "Tap", key: "1", sounds: [tapSound] },
{ slug: "press-sound", name: "Press", key: "2", sounds: [pressSound] },
{ slug: "type-sound", name: "Type", key: "3", sounds: [typeSound] },
{ slug: "select-sound", name: "Select", key: "4", sounds: [selectSound] },
{ slug: "toggle-sound", name: "Toggle", key: "5", sounds: [toggleOnSound, toggleOffSound] },
{ slug: "open-sound", name: "Open", key: "6", sounds: [openSound] },
{ slug: "close-sound", name: "Close", key: "7", sounds: [closeSound] },
{ slug: "navigate-sound", name: "Navigate", key: "8", sounds: [navigateSound] },
{ slug: "success-sound", name: "Success", key: "9", sounds: [successSound] },
{ slug: "error-sound", name: "Error", key: "0", sounds: [errorSound] },
// Letters Q to P
{ slug: "warning-sound", name: "Warning", key: "q", sounds: [warningSound] },
{ slug: "notify-sound", name: "Notify", key: "w", sounds: [notifySound] },
{ slug: "copy-sound", name: "Copy", key: "e", sounds: [copySound] },
{ slug: "delete-sound", name: "Delete", key: "r", sounds: [deleteSound] },
{ slug: "drop-sound", name: "Drop", key: "t", sounds: [dropSound] },
{ slug: "tick-sound", name: "Tick", key: "y", sounds: [tickSound] },
{ slug: "shutter-sound", name: "Shutter", key: "u", sounds: [shutterSound] },
{ slug: "bell-sound", name: "Bell", key: "i", sounds: [bellSound] },
{ slug: "switch-sound", name: "Switch", key: "o", sounds: [switchSound] },
{ slug: "burst-sound", name: "Burst", key: "p", sounds: [burstSound] },
// Letters A to L
{ slug: "camera-sound", name: "Camera", key: "a", sounds: [cameraSound] },
{ slug: "lock-sound", name: "Lock", key: "s", sounds: [lockSound] },
{ slug: "unlock-sound", name: "Unlock", key: "d", sounds: [unlockSound] },
{ slug: "coin-sound", name: "Coin", key: "f", sounds: [coinSound] },
{ slug: "chime-sound", name: "Chime", key: "g", sounds: [chimeSound] },
{ slug: "pop-sound", name: "Pop", key: "h", sounds: [popSound] },
{ slug: "trash-sound", name: "Trash", key: "j", sounds: [trashSound] },
{ slug: "heart-sound", name: "Heart", key: "k", sounds: [heartSound] },
{ slug: "buzz-sound", name: "Buzz", key: "l", sounds: [buzzSound] },
// Letters Z to M
{ slug: "swipe-sound", name: "Swipe", key: "z", sounds: [swipeSound] },
{ slug: "refresh-sound", name: "Refresh", key: "x", sounds: [refreshSound] },
{ slug: "snap-sound", name: "Snap", key: "c", sounds: [snapSound] },
{ slug: "bubble-sound", name: "Bubble", key: "v", sounds: [bubbleSound] },
{ slug: "expand-sound", name: "Expand", key: "b", sounds: [expandSound] },
{ slug: "collapse-sound", name: "Collapse", key: "n", sounds: [collapseSound] },
{ slug: "ping-sound", name: "Ping", key: "m", sounds: [pingSound] },
// Productivity & Interaction Pack
{ slug: "check-sound", name: "Check", sounds: [checkSound] },
{ slug: "send-sound", name: "Send", sounds: [sendSound] },
{ slug: "receive-sound", name: "Receive", sounds: [receiveSound] },
{ slug: "star-sound", name: "Star", sounds: [starSound] },
{ slug: "lift-sound", name: "Lift", sounds: [liftSound] },
{ slug: "dock-sound", name: "Dock", sounds: [dockSound] },
{ slug: "connect-sound", name: "Connect", sounds: [connectSound] },
{ slug: "disconnect-sound", name: "Disconnect", sounds: [disconnectSound] },
{ slug: "dismiss-sound", name: "Dismiss", sounds: [dismissSound] },
{ slug: "reveal-sound", name: "Reveal", sounds: [revealSound] },
{ slug: "timer-sound", name: "Timer", sounds: [timerSound] },
{ slug: "whisper-sound", name: "Whisper", sounds: [whisperSound] },
];
TSXcomponents/previews/sounds/sound-pad.tsx
"use client";
import { motion, useReducedMotion } from "motion/react";
import { type ReactNode, useEffect, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import type { Sound } from "@/lib/sounds/engine";
import { cn } from "@/lib/utils";
const BARS = 32;
const SAMPLE_RATE = 22050;
const peaksCache = new WeakMap<Sound, number[]>();
/** Renders a sound offline and measures its loudness in `BARS` slices. */
async function measurePeaks(sound: Sound) {
const cached = peaksCache.get(sound);
if (cached) return cached;
const length = Math.ceil(sound.duration * SAMPLE_RATE);
const context = new OfflineAudioContext(1, length, SAMPLE_RATE);
sound.render({ context, destination: context.destination, when: 0, volume: 1, pitch: 1 });
const data = (await context.startRendering()).getChannelData(0);
const size = Math.max(1, Math.floor(data.length / BARS));
const peaks = Array.from({ length: BARS }, (_, bar) => {
let peak = 0;
for (let i = bar * size; i < Math.min(data.length, (bar + 1) * size); i++) {
peak = Math.max(peak, Math.abs(data[i]));
}
return peak;
});
const max = Math.max(...peaks) || 1;
const normalized = peaks.map((peak) => peak / max);
peaksCache.set(sound, normalized);
return normalized;
}
function usePeaks(sound: Sound) {
const [peaks, setPeaks] = useState<number[] | null>(() => peaksCache.get(sound) ?? null);
useEffect(() => {
if (typeof OfflineAudioContext === "undefined") return;
let live = true;
measurePeaks(sound)
.then((next) => live && setPeaks(next))
.catch(() => undefined);
return () => {
live = false;
};
}, [sound]);
return peaks;
}
function Bars({ peaks, className }: { peaks: number[] | null; className: string }) {
return (
<div aria-hidden="true" className="absolute inset-0 flex items-center gap-[3px]">
{Array.from({ length: BARS }, (_, i) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-length bars.
key={i}
className={cn("min-h-[3px] flex-1 rounded-full", className)}
style={{ height: peaks ? `${Math.max(6, peaks[i] * 100)}%` : "6%" }}
/>
))}
</div>
);
}
/**
* A sound's real waveform, drawn from an offline render. Each new `pulse`
* lights the bars and runs a playhead across for the sound's length.
*/
export function SoundWave({
sound,
pulse,
className,
}: {
sound: Sound;
pulse: number;
className?: string;
}) {
const peaks = usePeaks(sound);
const reduce = useReducedMotion();
// Short sounds still get a sweep the eye can follow.
const sweep = Math.max(0.3, sound.duration);
return (
<div className={cn("relative h-12 w-full overflow-hidden", className)}>
<Bars
peaks={peaks}
className={cn(
"bg-muted-foreground/25 transition-[opacity,background-color] duration-300 group-hover/pad:bg-muted-foreground/45 dark:bg-muted-foreground/35 dark:group-hover/pad:bg-muted-foreground/55",
peaks ? "opacity-100" : "opacity-50",
)}
/>
{pulse > 0 ? (
<motion.div
key={pulse}
className="absolute inset-0"
initial={{ opacity: 1 }}
animate={{ opacity: 0 }}
transition={{ duration: sweep + 0.25, ease: EASE_OUT }}
>
<Bars peaks={peaks} className="bg-primary" />
</motion.div>
) : null}
{pulse > 0 && !reduce ? (
<motion.div
key={`head-${pulse}`}
aria-hidden="true"
className="absolute inset-y-0 left-0 w-full"
initial={{ x: "0%", opacity: 1 }}
animate={{ x: "100%", opacity: 0 }}
transition={{ duration: sweep, ease: "linear", opacity: { duration: sweep, ease: EASE_OUT } }}
>
<span className="absolute inset-y-0 left-0 w-px bg-primary" />
</motion.div>
) : null}
</div>
);
}
export interface SoundPadProps {
name: string;
/** The sound drawn in the waveform. */
sound: Sound;
/** Bumped on every play to run the waveform animation. */
pulse: number;
onPress: () => void;
/** Keyboard shortcut shown in the corner. */
keyHint?: string;
/** Replaces the plain name, for example with a link to the sound's page. */
nameSlot?: ReactNode;
className?: string;
}
/**
* A card that plays a sound when pressed and draws its waveform. Same frame
* as the site's component cards: a borderless card with an inset stage
* (rounded-3xl outside, rounded-2xl inside, 8px apart) and a name row.
*/
export function SoundPad({ name, sound, pulse, onPress, keyHint, nameSlot, className }: SoundPadProps) {
return (
<div
className={cn(
"group/pad relative flex flex-col rounded-3xl bg-card transition-transform duration-150 ease-out has-[button:active]:scale-[0.98] motion-reduce:has-[button:active]:scale-100",
className,
)}
>
<button
type="button"
onClick={onPress}
aria-label={`Play ${name}`}
className="absolute inset-0 z-10 rounded-3xl outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
/>
<div className="pointer-events-none relative m-2 mb-0 rounded-2xl bg-background px-5 py-6">
<SoundWave sound={sound} pulse={pulse} className="h-10" />
{keyHint ? (
<kbd className="absolute top-2 right-2 hidden size-5 items-center justify-center rounded-full bg-muted font-sans text-[10px] font-medium uppercase text-muted-foreground sm:inline-flex">
{keyHint}
</kbd>
) : null}
</div>
<div className="flex min-w-0 items-center justify-between gap-2 px-4 py-3.5">
<span className="relative z-20 truncate font-display text-base font-medium tracking-tight text-foreground">
{nameSlot ?? name}
</span>
<span className="pointer-events-none shrink-0 whitespace-nowrap text-xs text-muted-foreground tabular-nums">
{Math.round(sound.duration * 1000)} ms
</span>
</div>
</div>
);
}
/** Plays `sounds` in turn and tracks the pulse for one pad. */
export function useSoundPad(sounds: Sound[]) {
const [state, setState] = useState({ index: 0, pulse: 0 });
const play = () => {
sounds[state.index % sounds.length].play();
setState((current) => ({ index: current.index + 1, pulse: current.pulse + 1 }));
};
// The waveform shows the sound that just played.
const shown = sounds[(state.index + sounds.length - (state.pulse > 0 ? 1 : 0)) % sounds.length];
return { play, pulse: state.pulse, sound: shown };
}
/** One sound on its own page: a single large pad. */
export function SoundPreviewPad({ name, sounds }: { name: string; sounds: Sound[] }) {
const pad = useSoundPad(sounds);
return (
<div className="flex w-full justify-center px-4">
<SoundPad
name={sounds.length > 1 ? `${name} (${pad.sound.name.toLowerCase()})` : name}
sound={pad.sound}
pulse={pad.pulse}
onPress={pad.play}
className="w-full max-w-sm"
/>
</div>
);
}
PropTypeDefault
enabled?booleanFalse mutes every beUI sound under the provider.
Default
truevolume?number0 to 1, scales every beUI sound.
Default
1PropTypeDefault
enabled?booleanFalse makes play do nothing, for a component's sound prop.
Default
truevolume?number0 to 1 for this sound, on top of the provider volume.
Default
1Tap Sound
A fingertip on glass: a crisp contact, a small glass ring and a soft knock, for taps and plain clicks.
Press Sound
A physical button: a switch click over a soft thump and a little casing ring, for buttons.
Type Sound
A keystroke with a click, a spring and a soft thock, at a little random pitch, for text fields, search and chat inputs.
Updated