# Sound

Tactile synthesized sounds for UI95 components: one shared AudioContext, sounds configured in sounds.json, played by event delegation on each component's data-slot.

Source: https://www.ui95.dev/ui/sound

## Installation

```bash
npx shadcn@latest add https://www.ui95.dev/r/sound.json
```

Run it in a Radix shadcn project that already has the UI95 theme.

`lib/sound/types.ts`

```tsx
export type SoundWave = "sine" | "square" | "blend" | "noise"

export type SoundFilter = {
  type: "lowpass" | "highpass" | "bandpass"
  frequency: number
  q: number
}

export type SoundLayer = {
  wave: SoundWave
  frequency: number
  frequencyEnd?: number
  pitchTime?: number
  pitchSteps?: number
  sineShare?: number
  attack: number
  decay: number
  curve?: number
  gain: number
  delay?: number
  filter?: SoundFilter
}

export type SoundCrush = {
  sampleRate?: number
  bits?: number
  gainSteps?: number
  oneBit?: boolean
}

export type SoundJitter = { cents: number; gainDb: number; decay: number }

export type SoundDetentPolicy = "spread" | "collapse" | "per-event"

export type SoundDetent = {
  step: number
  minGap: number
  maxAhead: number
  policy: SoundDetentPolicy
  pitchFollow: number
}

export type SoundPatch = {
  note?: string
  layers: SoundLayer[]
  crush?: SoundCrush
  jitter?: SoundJitter
  gain?: number
  detent?: SoundDetent
}

export type SoundLoopSettings = {
  source: "noise" | "square" | "sine"
  frequency: number
  filter: "lowpass" | "bandpass" | "highpass"
  filterLow: number
  filterHigh: number
  q: number
  levelMin: number
  levelMax: number
  fullSpeed: number
  gate: number
  fps: number
  smoothing: number
  stopRamp: number
}

export type SoundLoop = { note?: string; loop: SoundLoopSettings }

export type SoundEntry = SoundPatch | SoundLoop | false

export type SoundsConfig = {
  $schema?: string
  enabled?: boolean
  volume?: number
  reducedMotion?: "thin" | "mute" | "ignore"
  sounds: Record<string, SoundEntry>
}

export function isSoundLoop(entry: SoundEntry | undefined): entry is SoundLoop {
  return typeof entry === "object" && "loop" in entry
}

export function isSoundPatch(entry: SoundEntry | undefined): entry is SoundPatch {
  return typeof entry === "object" && "layers" in entry
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value)
}

export function readSoundsConfig(value: unknown): SoundsConfig {
  if (!isRecord(value) || !isRecord(value.sounds)) {
    throw new Error("sounds.json needs a \"sounds\" object")
  }
  for (const [key, entry] of Object.entries(value.sounds)) {
    if (entry === false) {
      continue
    }
    if (!isRecord(entry) || (!Array.isArray(entry.layers) && !isRecord(entry.loop))) {
      throw new Error(`sounds.json "${key}" needs "layers", "loop" or false`)
    }
  }
  return value as SoundsConfig
}
```

`lib/sound/render.ts`

```tsx
import type { SoundFilter, SoundJitter, SoundLayer, SoundPatch } from "./types"

export type RenderOptions = {
  sampleRate: number
  jitter: boolean
  random?: () => number
}

export const DEFAULT_JITTER: SoundJitter = { cents: 35, gainDb: 1.5, decay: 0.12 }

const TAIL_SECONDS = 0.006
const GUARD_SECONDS = 0.001

type Biquad = { b0: number; b1: number; b2: number; a1: number; a2: number }

function designBiquad(spec: SoundFilter, sampleRate: number): Biquad {
  const omega = (2 * Math.PI * Math.min(spec.frequency, sampleRate * 0.45)) / sampleRate
  const cos = Math.cos(omega)
  const alpha = Math.sin(omega) / (2 * spec.q)
  const a0 = 1 + alpha
  const feedback = { a1: (-2 * cos) / a0, a2: (1 - alpha) / a0 }
  if (spec.type === "lowpass") {
    return { b0: (1 - cos) / 2 / a0, b1: (1 - cos) / a0, b2: (1 - cos) / 2 / a0, ...feedback }
  }
  if (spec.type === "highpass") {
    return { b0: (1 + cos) / 2 / a0, b1: -(1 + cos) / a0, b2: (1 + cos) / 2 / a0, ...feedback }
  }
  return { b0: alpha / a0, b1: 0, b2: -alpha / a0, ...feedback }
}

function applyBiquad(samples: Float32Array, start: number, end: number, filter: Biquad) {
  let x1 = 0
  let x2 = 0
  let y1 = 0
  let y2 = 0
  for (let index = start; index < end; index += 1) {
    const x0 = samples[index]
    const y0 = filter.b0 * x0 + filter.b1 * x1 + filter.b2 * x2 - filter.a1 * y1 - filter.a2 * y2
    samples[index] = y0
    x2 = x1
    x1 = x0
    y2 = y1
    y1 = y0
  }
}

function readFrequency(layer: SoundLayer, time: number, scale: number): number {
  const start = layer.frequency * scale
  const end = (layer.frequencyEnd ?? layer.frequency) * scale
  const pitchTime = layer.pitchTime ?? 0
  if (pitchTime <= 0 || start === end) {
    return start
  }
  const progress = Math.min(time / pitchTime, 1)
  const stepped = layer.pitchSteps ? Math.floor(progress * layer.pitchSteps) / layer.pitchSteps : progress
  return start * Math.pow(end / start, stepped)
}

function readEnvelope(layer: SoundLayer, time: number, gainSteps: number | undefined): number {
  const attack = Math.max(layer.attack, 0)
  let level: number
  if (time < attack) {
    level = time / attack
  } else {
    const progress = (time - attack) / layer.decay
    level = progress >= 1 ? 0 : Math.pow(1 - progress, layer.curve ?? 3)
  }
  if (gainSteps) {
    return Math.ceil(level * gainSteps - 1e-9) / gainSteps
  }
  return level
}

function readOscillator(layer: SoundLayer, phase: number, random: () => number): number {
  if (layer.wave === "noise") {
    return random() * 2 - 1
  }
  const sine = Math.sin(2 * Math.PI * phase)
  if (layer.wave === "sine") {
    return sine
  }
  const square = phase % 1 < 0.5 ? 1 : -1
  if (layer.wave === "square") {
    return square
  }
  const share = layer.sineShare ?? 0.5
  return sine * share + square * (1 - share)
}

function readLength(layer: SoundLayer): number {
  return (layer.delay ?? 0) + Math.max(layer.attack, 0) + layer.decay + (layer.filter ? TAIL_SECONDS : 0)
}

export function readPatchDuration(patch: SoundPatch): number {
  return Math.max(0, ...patch.layers.map(readLength)) + GUARD_SECONDS
}

export function renderSoundPatch(patch: SoundPatch, options: RenderOptions): Float32Array {
  const random = options.random ?? Math.random
  const jitter = options.jitter ? (patch.jitter ?? DEFAULT_JITTER) : null
  const centsShift = jitter ? (random() * 2 - 1) * jitter.cents : 0
  const gainShift = jitter ? Math.pow(10, ((random() * 2 - 1) * jitter.gainDb) / 20) : 1
  const decayShift = jitter ? 1 + (random() * 2 - 1) * jitter.decay : 1
  const frequencyScale = Math.pow(2, centsShift / 1200)
  const sampleRate = options.sampleRate
  const length = Math.max(1, Math.ceil(readPatchDuration(patch) * sampleRate))
  const output = new Float32Array(length)
  const scratch = new Float32Array(length)
  const crush = patch.crush

  for (const sourceLayer of patch.layers) {
    const layer = { ...sourceLayer, decay: Math.max(sourceLayer.decay * decayShift, 1e-4) }
    const offset = Math.round((layer.delay ?? 0) * sampleRate)
    const layerLength = Math.min(Math.ceil(readLength(layer) * sampleRate), length - offset)
    const voiced = Math.ceil((Math.max(layer.attack, 0) + layer.decay) * sampleRate)
    scratch.fill(0)
    let phase = 0
    for (let index = 0; index < Math.min(layerLength, voiced); index += 1) {
      const time = index / sampleRate
      phase += readFrequency(layer, time, frequencyScale) / sampleRate
      scratch[offset + index] = readOscillator(layer, phase, random) * readEnvelope(layer, time, crush?.gainSteps) * layer.gain
    }
    if (layer.filter) {
      applyBiquad(scratch, offset, offset + layerLength, designBiquad(layer.filter, sampleRate))
    }
    for (let index = offset; index < offset + layerLength; index += 1) {
      output[index] += scratch[index]
    }
  }

  if (crush?.sampleRate) {
    const hold = sampleRate / crush.sampleRate
    let held = 0
    let counter = hold
    for (let index = 0; index < length; index += 1) {
      if (counter >= hold) {
        held = output[index]
        counter -= hold
      }
      output[index] = held
      counter += 1
    }
  }
  if (crush?.bits) {
    const levels = Math.pow(2, crush.bits - 1)
    for (let index = 0; index < length; index += 1) {
      output[index] = Math.round(output[index] * levels) / levels
    }
  }
  if (crush?.oneBit) {
    for (let index = 0; index < length; index += 1) {
      const value = output[index]
      output[index] = Math.abs(value) < 0.04 ? 0 : Math.sign(value) * 0.5
    }
  }

  const patchGain = (patch.gain ?? 1) * gainShift
  const guard = Math.min(Math.ceil(GUARD_SECONDS * sampleRate), length)
  for (let index = 0; index < length; index += 1) {
    const fromEnd = length - 1 - index
    output[index] *= patchGain * (fromEnd < guard ? fromEnd / guard : 1)
  }
  return output
}
```

`lib/sound/sound-engine.ts`

```tsx
import { renderSoundPatch } from "./render"
import {
  isSoundLoop,
  isSoundPatch,
  type SoundDetent,
  type SoundLoopSettings,
  type SoundPatch,
  type SoundsConfig,
} from "./types"

export type SoundPlayOptions = { when?: number; rate?: number }

const ENABLED_KEY = "nostalgui:sound-enabled"
const VARIANTS = 6
const MAX_VOICES = 12
const DEFAULT_VOLUME = 0.6
const DEFAULT_DETENT: SoundDetent = { step: 1, minGap: 18, maxAhead: 60, policy: "spread", pitchFollow: 0 }
const EMPTY_CONFIG: SoundsConfig = { sounds: {} }

function readStoredEnabled(): boolean | null {
  try {
    const stored = window.localStorage.getItem(ENABLED_KEY)
    return stored === null ? null : stored === "true"
  } catch {
    return null
  }
}

export class SoundLoopHandle {
  private gain: GainNode
  private filter: BiquadFilterNode
  private source: AudioScheduledSourceNode
  private distance = 0
  private timer: number
  private stopped = false

  constructor(
    private context: AudioContext,
    destination: AudioNode,
    private settings: SoundLoopSettings,
    noise: AudioBuffer,
  ) {
    this.gain = context.createGain()
    this.gain.gain.value = 0
    this.filter = context.createBiquadFilter()
    this.filter.type = settings.filter
    this.filter.frequency.value = settings.filterLow
    this.filter.Q.value = settings.q
    this.filter.connect(this.gain)
    this.gain.connect(destination)
    if (settings.source === "noise") {
      const source = context.createBufferSource()
      source.buffer = noise
      source.loop = true
      this.source = source
    } else {
      const oscillator = context.createOscillator()
      oscillator.type = settings.source
      oscillator.frequency.value = settings.frequency
      this.source = oscillator
    }
    this.source.connect(this.filter)
    this.source.start()
    const fps = Math.max(settings.fps, 1)
    this.timer = window.setInterval(() => {
      this.setSpeed(this.distance * fps)
      this.distance = 0
    }, 1000 / fps)
  }

  move(pixels: number) {
    this.distance += pixels
  }

  private setSpeed(speed: number) {
    const settings = this.settings
    const now = this.context.currentTime
    const amount = Math.min(speed / Math.max(settings.fullSpeed, 1), 1)
    const level = speed < settings.gate ? 0 : settings.levelMin + amount * (settings.levelMax - settings.levelMin)
    this.gain.gain.setTargetAtTime(level, now, Math.max(settings.smoothing, 0.5) / 1000)
    this.filter.frequency.setValueAtTime(settings.filterLow + amount * (settings.filterHigh - settings.filterLow), now)
  }

  stop() {
    if (this.stopped) {
      return
    }
    this.stopped = true
    window.clearInterval(this.timer)
    const ramp = Math.max(this.settings.stopRamp, 1) / 1000
    const now = this.context.currentTime
    this.gain.gain.cancelScheduledValues(now)
    this.gain.gain.setValueAtTime(this.gain.gain.value, now)
    this.gain.gain.linearRampToValueAtTime(0, now + ramp)
    this.source.stop(now + ramp + 0.005)
    this.source.onended = () => {
      this.source.disconnect()
      this.filter.disconnect()
      this.gain.disconnect()
    }
  }
}

export class SoundEngine {
  private static instance: SoundEngine | null = null

  static get(): SoundEngine | null {
    if (typeof window === "undefined" || typeof window.AudioContext === "undefined") {
      return null
    }
    SoundEngine.instance ??= new SoundEngine()
    return SoundEngine.instance
  }

  private base: SoundsConfig = EMPTY_CONFIG
  private override: SoundsConfig | null = null
  private context: AudioContext | null = null
  private master: GainNode | null = null
  private noise: AudioBuffer | null = null
  private variants = new Map<string, { buffers: AudioBuffer[]; next: number }>()
  private nextTick = new Map<string, number>()
  private storedEnabled: boolean | null = readStoredEnabled()
  private listeners = new Set<() => void>()
  private warned = new Set<string>()
  private voices = 0
  private reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)")

  get config(): SoundsConfig {
    return this.override ?? this.base
  }

  get enabled(): boolean {
    const muted = this.reducedMotion.matches && this.config.reducedMotion === "mute"
    return !muted && (this.storedEnabled ?? this.config.enabled !== false)
  }

  configure(config: SoundsConfig) {
    this.base = config
    this.refresh()
  }

  setOverride(config: SoundsConfig | null) {
    this.override = config
    this.refresh()
  }

  setEnabled(enabled: boolean) {
    this.storedEnabled = enabled
    try {
      window.localStorage.setItem(ENABLED_KEY, String(enabled))
    } catch {
      this.warned.add(ENABLED_KEY)
    }
    if (enabled) {
      this.unlock()
    }
    this.notify()
  }

  subscribe(listener: () => void): () => void {
    this.listeners.add(listener)
    return () => {
      this.listeners.delete(listener)
    }
  }

  unlock(): AudioContext | null {
    if (!this.enabled) {
      return null
    }
    if (!this.context) {
      const context = new AudioContext({ latencyHint: "interactive" })
      const master = context.createGain()
      master.gain.value = this.config.volume ?? DEFAULT_VOLUME
      master.connect(context.destination)
      const noise = context.createBuffer(1, context.sampleRate, context.sampleRate)
      const channel = noise.getChannelData(0)
      for (let index = 0; index < channel.length; index += 1) {
        channel[index] = Math.random() * 2 - 1
      }
      this.context = context
      this.master = master
      this.noise = noise
    }
    if (this.context.state === "suspended") {
      void this.context.resume()
    }
    return this.context
  }

  get now(): number {
    return this.context?.currentTime ?? 0
  }

  has(key: string): boolean {
    const entry = this.config.sounds[key]
    return entry !== undefined && entry !== false
  }

  detent(key: string): SoundDetent {
    const entry = this.config.sounds[key]
    return isSoundPatch(entry) && entry.detent ? entry.detent : DEFAULT_DETENT
  }

  play(key: string, options: SoundPlayOptions = {}): boolean {
    const entry = this.config.sounds[key]
    if (!isSoundPatch(entry)) {
      this.warnMissing(key, entry === undefined)
      return false
    }
    const context = this.unlock()
    if (!context) {
      return false
    }
    const buffer = this.readVariant(key, context)
    return buffer ? this.start(context, buffer, options) : false
  }

  playPatch(patch: SoundPatch, options: SoundPlayOptions = {}): boolean {
    const context = this.unlock()
    if (!context) {
      return false
    }
    return this.start(context, this.toBuffer(context, patch), options)
  }

  private start(context: AudioContext, buffer: AudioBuffer, options: SoundPlayOptions): boolean {
    if (!this.master || this.voices >= MAX_VOICES) {
      return false
    }
    const source = context.createBufferSource()
    source.buffer = buffer
    source.playbackRate.value = options.rate ?? 1
    source.connect(this.master)
    source.start(Math.max(options.when ?? 0, context.currentTime))
    this.voices += 1
    source.onended = () => {
      this.voices -= 1
      source.disconnect()
    }
    return true
  }

  private toBuffer(context: AudioContext, patch: SoundPatch): AudioBuffer {
    const samples = renderSoundPatch(patch, { sampleRate: context.sampleRate, jitter: true })
    const buffer = context.createBuffer(1, samples.length, context.sampleRate)
    buffer.copyToChannel(new Float32Array(samples), 0)
    return buffer
  }

  step(key: string, steps: number, position = 0.5) {
    if (steps <= 0 || !this.enabled) {
      return
    }
    const thin = this.isThin()
    const detent = this.detent(key)
    const policy = thin ? "collapse" : detent.policy
    const gap = (thin ? Math.max(detent.minGap, 60) : detent.minGap) / 1000
    const rate = 1 + (position * 2 - 1) * detent.pitchFollow
    const context = this.unlock()
    if (!context) {
      return
    }
    const now = context.currentTime
    const free = this.nextTick.get(key) ?? 0
    if (policy === "per-event") {
      this.play(key, { rate })
      return
    }
    if (policy === "collapse") {
      if (now >= free - gap * 0.5 && this.play(key, { rate })) {
        this.nextTick.set(key, now + gap)
      }
      return
    }
    let when = Math.max(now, free)
    for (let index = 0; index < steps && when <= now + detent.maxAhead / 1000; index += 1) {
      this.play(key, { when, rate })
      when += gap
    }
    this.nextTick.set(key, when)
  }

  startLoop(key: string): SoundLoopHandle | null {
    const entry = this.config.sounds[key]
    if (!isSoundLoop(entry)) {
      this.warnMissing(key, entry === undefined)
      return null
    }
    if (this.isThin()) {
      return null
    }
    const context = this.unlock()
    if (!context || !this.master || !this.noise) {
      return null
    }
    return new SoundLoopHandle(context, this.master, entry.loop, this.noise)
  }

  private isThin(): boolean {
    return this.reducedMotion.matches && (this.config.reducedMotion ?? "thin") === "thin"
  }

  private readVariant(key: string, context: AudioContext): AudioBuffer | null {
    const entry = this.config.sounds[key]
    if (!isSoundPatch(entry)) {
      return null
    }
    let cached = this.variants.get(key)
    if (!cached) {
      const buffers = Array.from({ length: VARIANTS }, () => this.toBuffer(context, entry))
      cached = { buffers, next: Math.floor(Math.random() * VARIANTS) }
      this.variants.set(key, cached)
    }
    const buffer = cached.buffers[cached.next % cached.buffers.length]
    cached.next += 1 + Math.floor(Math.random() * (VARIANTS - 1))
    return buffer
  }

  private warnMissing(key: string, missing: boolean) {
    if (!missing || this.warned.has(key) || process.env.NODE_ENV === "production") {
      return
    }
    this.warned.add(key)
    console.warn(`UI95 sound "${key}" is not in sounds.json. Run: node scripts/95-sound-lib.mjs sync`)
  }

  private refresh() {
    this.variants.clear()
    if (this.master && this.context) {
      this.master.gain.setTargetAtTime(this.config.volume ?? DEFAULT_VOLUME, this.context.currentTime, 0.01)
    }
    this.notify()
  }

  private notify() {
    for (const listener of this.listeners) {
      listener()
    }
  }
}
```

`lib/sound/sound-slots.ts`

```tsx
import type { SoundEngine, SoundLoopHandle } from "./sound-engine"

export type SoundGesture = "press" | "toggle" | "select" | "menu" | "steps" | "drag" | "type"

type SlotRule = { key: (element: Element) => string; gesture: SoundGesture | ((element: Element) => SoundGesture) }

const SMALL_SIZES = new Set(["xs", "icon", "icon-xs", "icon-sm"])

const fixed = (key: string) => () => key

export const soundSlots: Record<string, SlotRule> = {
  button: { key: (element) => (SMALL_SIZES.has(element.getAttribute("data-size") ?? "") ? "small-button" : "button"), gesture: "press" },
  "cta-button": { key: fixed("keycap"), gesture: "press" },
  checkbox: { key: fixed("checkbox"), gesture: "toggle" },
  switch: { key: fixed("switch"), gesture: "toggle" },
  "radio-group-item": { key: fixed("radio"), gesture: "select" },
  "tabs-trigger": { key: fixed("tab"), gesture: "select" },
  "dropdown-menu-item": { key: fixed("menu"), gesture: "menu" },
  "dropdown-menu-checkbox-item": { key: fixed("menu"), gesture: "menu" },
  "dropdown-menu-radio-item": { key: fixed("menu"), gesture: "menu" },
  "menubar-trigger": { key: fixed("menu"), gesture: "menu" },
  "menubar-sub-trigger": { key: fixed("menu"), gesture: "menu" },
  "menubar-item": { key: fixed("menu"), gesture: "menu" },
  "menubar-checkbox-item": { key: fixed("menu"), gesture: "menu" },
  "menubar-radio-item": { key: fixed("menu"), gesture: "menu" },
  "select-item": { key: fixed("menu"), gesture: "menu" },
  "context-menu-item": { key: fixed("menu"), gesture: "menu" },
  "context-menu-checkbox-item": { key: fixed("menu"), gesture: "menu" },
  "context-menu-radio-item": { key: fixed("menu"), gesture: "menu" },
  "command-item": { key: fixed("menu"), gesture: "menu" },
  toggle: { key: fixed("toggle"), gesture: "toggle" },
  "toggle-group-item": { key: fixed("toggle"), gesture: (element) => (element.getAttribute("role") === "radio" ? "select" : "toggle") },
  "taskbar-start": { key: fixed("taskbar"), gesture: "press" },
  "taskbar-task": { key: fixed("taskbar"), gesture: "press" },
  "carousel-previous": { key: (element) => (SMALL_SIZES.has(element.getAttribute("data-size") ?? "") ? "small-button" : "button"), gesture: "press" },
  "carousel-next": { key: (element) => (SMALL_SIZES.has(element.getAttribute("data-size") ?? "") ? "small-button" : "button"), gesture: "press" },
  slider: { key: fixed("slider"), gesture: "steps" },
  "rotary-knob": { key: fixed("knob"), gesture: "steps" },
  "resizable-handle": { key: fixed("slider"), gesture: "steps" },
  "sidebar-menu-button": { key: (element) => (element.getAttribute("data-size") === "sm" ? "small-button" : "button"), gesture: "press" },
  "sidebar-menu-sub-button": { key: fixed("small-button"), gesture: "press" },
  window: { key: fixed("drag"), gesture: "drag" },
  input: { key: fixed("typewriter"), gesture: "type" },
  textarea: { key: fixed("typewriter"), gesture: "type" },
  "input-group-control": { key: fixed("typewriter"), gesture: "type" },
  "command-input": { key: fixed("typewriter"), gesture: "type" },
}

const BARE_ELEMENT = { getAttribute: () => null } as unknown as Element

const keyGestures = new Map<string, SoundGesture>(
  Object.values(soundSlots).flatMap((rule) => (typeof rule.gesture === "string" ? [[rule.key(BARE_ELEMENT), rule.gesture] as const] : []))
)

const UNLOCK_EVENTS = ["pointerup", "touchend", "click", "keydown"] as const

type Target = { element: Element; key: string; gesture: SoundGesture }

const BUTTON_LIKE_SUFFIXES = ["-trigger", "-action", "-cancel", "-close", "-link"]
const RECENT_MS = 400
const DISABLED = ":disabled, [aria-disabled='true'], [data-disabled]"
const TEXT_ENTRY = "textarea, input:not([type]), input:is([type='text'], [type='search'], [type='email'], [type='url'], [type='tel'], [type='password'], [type='number'])"

function typedStroke(event: InputEvent): string | null {
  if (event.isComposing) {
    return null
  }
  if (event.inputType === "insertLineBreak" || event.inputType === "insertParagraph") {
    return "return"
  }
  if (event.inputType === "insertText") {
    return event.data === " " ? "space" : "key"
  }
  if (event.inputType.startsWith("delete") || event.inputType.startsWith("insertFrom") || event.inputType === "insertCompositionText") {
    return "key"
  }
  return null
}

function resolveTarget(start: EventTarget | null): Target | null {
  let node = start instanceof Element ? start : null
  while (node) {
    const sound = node.getAttribute("data-sound")
    if (sound === "none") {
      return null
    }
    const slot = node.getAttribute("data-slot")
    const rule = slot ? (soundSlots[slot] ?? (BUTTON_LIKE_SUFFIXES.some((suffix) => slot.endsWith(suffix)) ? soundSlots.button : undefined)) : undefined
    const gesture = typeof rule?.gesture === "function" ? rule.gesture(node) : rule?.gesture
    if (sound) {
      return { element: node, key: sound, gesture: gesture ?? keyGestures.get(sound) ?? "press" }
    }
    if (rule && gesture) {
      return { element: node, key: rule.key(node), gesture }
    }
    node = node.parentElement
  }
  return null
}

function isOn(element: Element, attribute: string): boolean {
  return element.getAttribute(attribute) === "true"
}

function toggleAttribute(element: Element): string {
  return element.hasAttribute("aria-pressed") ? "aria-pressed" : "aria-checked"
}

export function attachSoundSlots(engine: SoundEngine, root: Document = document): () => void {
  const recent = new WeakMap<Element, number>()
  const values = new WeakMap<Element, { value: number; carry: number }>()
  let pressed: Target | null = null
  let dragLoop: SoundLoopHandle | null = null
  let dragKey = ""
  let lastPointer: { x: number; y: number } | null = null

  const markRecent = (element: Element) => recent.set(element, performance.now())
  const takeRecent = (element: Element) => {
    const time = recent.get(element)
    recent.delete(element)
    return time !== undefined && performance.now() - time < RECENT_MS
  }

  const release = () => {
    if (pressed) {
      engine.play(`${pressed.key}.release`)
      pressed = null
    }
  }

  const unlockAudio = () => {
    if (engine.enabled) {
      engine.unlock()
    }
  }

  const onPointerDown = (event: PointerEvent) => {
    if (!engine.enabled || event.button !== 0) {
      return
    }
    engine.unlock()
    lastPointer = { x: event.clientX, y: event.clientY }
    const target = resolveTarget(event.target)
    if (!target || target.element.matches(DISABLED)) {
      return
    }
    const { element, key, gesture } = target
    if (gesture === "press") {
      pressed = target
      engine.play(`${key}.press`)
    } else if (gesture === "toggle") {
      markRecent(element)
      engine.play(`${key}.${isOn(element, toggleAttribute(element)) ? "off" : "on"}`)
    } else if (gesture === "select") {
      const attribute = element.hasAttribute("aria-selected") ? "aria-selected" : "aria-checked"
      if (!isOn(element, attribute)) {
        markRecent(element)
        engine.play(`${key}.select`)
      }
    }
  }

  const onPointerUp = (event: PointerEvent) => {
    release()
    if (!engine.enabled || event.button !== 0) {
      return
    }
    const target = resolveTarget(event.target)
    if (target?.gesture === "menu" && !target.element.matches(DISABLED)) {
      engine.play(`${target.key}.select`)
    }
  }

  const onPointerMove = (event: PointerEvent) => {
    if (dragLoop && lastPointer) {
      dragLoop.move(Math.hypot(event.clientX - lastPointer.x, event.clientY - lastPointer.y))
    }
    lastPointer = { x: event.clientX, y: event.clientY }
  }

  const onKeyDown = (event: KeyboardEvent) => {
    if (!engine.enabled || event.repeat || (event.key !== " " && event.key !== "Enter")) {
      return
    }
    const target = resolveTarget(event.target)
    if (!target || target.element.matches(DISABLED)) {
      return
    }
    if (target.gesture === "press") {
      pressed = target
      engine.play(`${target.key}.press`)
    } else if (target.gesture === "menu") {
      engine.play(`${target.key}.select`)
    }
  }

  const onInput = (event: Event) => {
    if (!engine.enabled || !(event instanceof InputEvent) || !(event.target instanceof Element) || !event.target.matches(TEXT_ENTRY)) {
      return
    }
    const target = resolveTarget(event.target)
    const stroke = target?.gesture === "type" ? typedStroke(event) : null
    if (target && stroke) {
      engine.play(`${target.key}.${stroke}`)
    }
  }

  const onKeyUp = (event: KeyboardEvent) => {
    if (event.key === " " || event.key === "Enter") {
      release()
    }
  }

  const onMutation = (records: MutationRecord[]) => {
    if (!engine.enabled) {
      return
    }
    for (const record of records) {
      const element = record.target
      if (!(element instanceof Element) || !record.attributeName) {
        continue
      }
      const attribute = record.attributeName
      const target = resolveTarget(element)
      if (!target) {
        continue
      }
      if (attribute === "data-dragging" && target.gesture === "drag" && target.element === element) {
        if (isOn(element, "data-dragging")) {
          dragLoop?.stop()
          dragKey = target.key
          engine.play(`${dragKey}.pickup`)
          dragLoop = engine.startLoop(`${dragKey}.friction`)
        } else if (dragKey) {
          dragLoop?.stop()
          dragLoop = null
          engine.play(`${dragKey}.drop`)
          dragKey = ""
        }
        continue
      }
      if (target.element !== element && target.gesture !== "steps") {
        continue
      }
      if (target.gesture === "toggle" && attribute === toggleAttribute(element)) {
        if (!takeRecent(element)) {
          engine.play(`${target.key}.${isOn(element, attribute) ? "on" : "off"}`)
        }
      } else if (target.gesture === "select" && (attribute === "aria-checked" || attribute === "aria-selected")) {
        if (isOn(element, attribute) && !takeRecent(element)) {
          engine.play(`${target.key}.select`)
        }
      } else if (target.gesture === "steps" && attribute === "aria-valuenow") {
        const value = Number(element.getAttribute("aria-valuenow"))
        const previous = values.get(element)
        if (!previous || !Number.isFinite(value)) {
          values.set(element, { value, carry: 0 })
          continue
        }
        const tickKey = `${target.key}.tick`
        const min = Number(element.getAttribute("aria-valuemin") ?? 0)
        const max = Number(element.getAttribute("aria-valuemax") ?? 100)
        const range = max > min ? max - min : 100
        const percent = (Math.abs(value - previous.value) / range) * 100
        const units = percent / Math.max(engine.detent(tickKey).step, 1e-6) + previous.carry
        const steps = Math.floor(units + 1e-9)
        values.set(element, { value, carry: units - steps })
        engine.step(tickKey, steps, max > min ? (value - min) / range : 0.5)
      }
    }
  }

  const primeSliders = () => {
    for (const thumb of root.querySelectorAll("[role='slider'][aria-valuenow]")) {
      if (!values.has(thumb)) {
        values.set(thumb, { value: Number(thumb.getAttribute("aria-valuenow")), carry: 0 })
      }
    }
  }

  const onFocusIn = () => primeSliders()
  const observer = new MutationObserver(onMutation)
  observer.observe(root.documentElement, {
    subtree: true,
    attributes: true,
    attributeFilter: ["aria-checked", "aria-pressed", "aria-selected", "aria-valuenow", "data-dragging"],
  })
  const options = { capture: true, passive: true }
  for (const type of UNLOCK_EVENTS) {
    root.addEventListener(type, unlockAudio, options)
  }
  root.addEventListener("pointerdown", onPointerDown, options)
  root.addEventListener("pointerdown", primeSliders, options)
  root.addEventListener("pointerup", onPointerUp, options)
  root.addEventListener("pointercancel", release, options)
  root.addEventListener("pointermove", onPointerMove, options)
  root.addEventListener("keydown", onKeyDown, options)
  root.addEventListener("keyup", onKeyUp, options)
  root.addEventListener("input", onInput, options)
  root.addEventListener("focusin", onFocusIn, options)

  return () => {
    observer.disconnect()
    dragLoop?.stop()
    for (const type of UNLOCK_EVENTS) {
      root.removeEventListener(type, unlockAudio, options)
    }
    root.removeEventListener("pointerdown", onPointerDown, options)
    root.removeEventListener("pointerdown", primeSliders, options)
    root.removeEventListener("pointerup", onPointerUp, options)
    root.removeEventListener("pointercancel", release, options)
    root.removeEventListener("pointermove", onPointerMove, options)
    root.removeEventListener("keydown", onKeyDown, options)
    root.removeEventListener("keyup", onKeyUp, options)
    root.removeEventListener("input", onInput, options)
    root.removeEventListener("focusin", onFocusIn, options)
  }
}
```

`lib/sound/config.ts`

```tsx
import soundsJson from "@/sounds.json"

import { readSoundsConfig, type SoundsConfig } from "./types"

export const soundsConfig: SoundsConfig = readSoundsConfig(soundsJson)
```

`hooks/use-sound.ts`

```tsx
"use client"

import { useCallback, useSyncExternalStore } from "react"

import { SoundEngine, type SoundPlayOptions } from "@/lib/sound/sound-engine"

function subscribe(listener: () => void): () => void {
  return SoundEngine.get()?.subscribe(listener) ?? (() => {})
}

function readEnabled(): boolean {
  return SoundEngine.get()?.enabled ?? false
}

function readServerEnabled(): boolean {
  return false
}

export function useSoundEnabled(): [boolean, (enabled: boolean) => void] {
  const enabled = useSyncExternalStore(subscribe, readEnabled, readServerEnabled)
  const setEnabled = useCallback((next: boolean) => SoundEngine.get()?.setEnabled(next), [])
  return [enabled, setEnabled]
}

export function useSound(key: string): (options?: SoundPlayOptions) => void {
  return useCallback((options?: SoundPlayOptions) => {
    SoundEngine.get()?.play(key, options)
  }, [key])
}
```

`components/ui/ui95-sounds.tsx`

```tsx
"use client"

import { useEffect } from "react"

import { soundsConfig } from "@/lib/sound/config"
import { SoundEngine } from "@/lib/sound/sound-engine"
import { attachSoundSlots } from "@/lib/sound/sound-slots"
import type { SoundsConfig } from "@/lib/sound/types"

type Ui95SoundsProps = {
  config?: SoundsConfig
}

function Ui95Sounds({ config = soundsConfig }: Ui95SoundsProps) {
  useEffect(() => {
    const engine = SoundEngine.get()
    if (!engine) {
      return
    }
    engine.configure(config)
    return attachSoundSlots(engine, document)
  }, [config])
  return null
}

export { Ui95Sounds }
```

`sounds.json`

```tsx
{
  "$schema": "https://www.ui95.dev/schema/sounds.json",
  "enabled": true,
  "volume": 0.6,
  "reducedMotion": "thin",
  "sounds": {}
}


```

`scripts/95-sound-lib.mjs`

```tsx
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from "node:fs"
import { basename, dirname, join, relative, resolve } from "node:path"
import { parseArgs } from "node:util"

const USAGE = `Usage: node scripts/95-sound-lib.mjs sync [items...] [options]

Adds the sounds of every installed UI95 component to sounds.json.
Entries already in sounds.json are kept as they are.

Options:
  --overwrite         replace existing entries with the registry defaults
  --registry <url>    item URL template, default: components.json registries["@ui95"]
  --file <path>       sounds.json location, default: where "@/sounds.json" resolves
  --dry-run           print the changes without writing
  -h, --help          show this help`

const CWD = process.cwd()

function fail(message) {
  console.error(`95-sound-lib: ${message}`)
  process.exit(1)
}

function readJson(path, label) {
  try {
    return JSON.parse(readFileSync(path, "utf8"))
  } catch (error) {
    fail(`could not read ${label} at ${relative(CWD, path) || path}: ${error.message}`)
  }
}

function stripJsonComments(text) {
  return text.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (match, comment) => (comment ? "" : match)).replace(/,(\s*[}\]])/g, "$1")
}

function readAliasRoot() {
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
    const path = join(CWD, name)
    if (!existsSync(path)) {
      continue
    }
    try {
      const config = JSON.parse(stripJsonComments(readFileSync(path, "utf8")))
      const options = config.compilerOptions ?? {}
      const target = options.paths?.["@/*"]?.[0]
      if (target) {
        return resolve(CWD, options.baseUrl ?? ".", target.replace(/\*$/, ""))
      }
    } catch {
      return CWD
    }
  }
  return CWD
}

function resolveAlias(alias, aliasRoot) {
  if (alias.startsWith("@/")) {
    return join(aliasRoot, alias.slice(2))
  }
  return resolve(CWD, alias)
}

function readRegistryTemplate(componentsJson, override) {
  const style = componentsJson.style ?? "radix-nova"
  if (override) {
    return { url: override, headers: {}, style }
  }
  const entry = componentsJson.registries?.["@ui95"]
  if (typeof entry === "string") {
    return { url: entry, headers: {}, style }
  }
  if (entry && typeof entry.url === "string") {
    const headers = Object.fromEntries(Object.entries(entry.headers ?? {}).map(([key, value]) => [key, String(value).replace(/\$\{(\w+)\}/g, (_, name) => process.env[name] ?? "")]))
    return { url: entry.url, headers, style }
  }
  fail('components.json has no registries["@ui95"]; pass --registry "https://host/r/{style}/{name}.json"')
}

async function fetchItem(registry, name) {
  const url = registry.url.replace("{name}", name).replace("{style}", registry.style)
  const response = await fetch(url, { headers: registry.headers })
  if (!response.ok) {
    fail(`GET ${url} answered ${response.status}`)
  }
  return response.json()
}

function localPathFor(file, aliases, aliasRoot) {
  const target = file.target
  if (target?.startsWith("~/")) {
    return join(CWD, target.slice(2))
  }
  const prefixes = { "@components/": aliases.components, "@ui/": aliases.ui, "@lib/": aliases.lib, "@hooks/": aliases.hooks }
  for (const [prefix, alias] of Object.entries(prefixes)) {
    if (target?.startsWith(prefix) && alias) {
      return join(resolveAlias(alias, aliasRoot), target.slice(prefix.length))
    }
  }
  const byType = {
    "registry:ui": aliases.ui,
    "registry:component": aliases.components,
    "registry:hook": aliases.hooks,
    "registry:lib": aliases.lib,
  }
  const alias = byType[file.type]
  return alias ? join(resolveAlias(alias, aliasRoot), basename(file.path)) : null
}

function isInstalled(item, aliases, aliasRoot) {
  const files = item.files ?? []
  const primary = files.find((file) => file.type === "registry:ui" || file.type === "registry:component") ?? files[0]
  const path = primary ? localPathFor(primary, aliases, aliasRoot) : null
  return path !== null && existsSync(path)
}

function schemaUrlFor(registryUrl) {
  try {
    return new URL("/schema/sounds.json", registryUrl.replace("{name}", "x")).toString()
  } catch {
    return undefined
  }
}

async function sync(names, options) {
  const componentsPath = join(CWD, "components.json")
  if (!existsSync(componentsPath)) {
    fail("run this from the project root, next to components.json")
  }
  const componentsJson = readJson(componentsPath, "components.json")
  const aliases = componentsJson.aliases ?? {}
  const aliasRoot = readAliasRoot()
  const registry = readRegistryTemplate(componentsJson, options.registry)
  const soundsPath = options.file ? resolve(CWD, options.file) : join(aliasRoot, "sounds.json")

  const index = await fetchItem(registry, "registry")
  const items = (index.items ?? []).filter((item) => Array.isArray(item.meta?.sounds) && item.meta.sounds.length > 0)
  const known = new Set(items.map((item) => item.name))
  for (const name of names) {
    if (!known.has(name)) {
      fail(`"${name}" is not a UI95 item with sounds. Items with sounds: ${[...known].join(", ")}`)
    }
  }
  const chosen = names.length > 0 ? items.filter((item) => names.includes(item.name)) : items.filter((item) => isInstalled(item, aliases, aliasRoot))

  const sounds = existsSync(soundsPath)
    ? readJson(soundsPath, "sounds.json")
    : { $schema: schemaUrlFor(registry.url), enabled: true, volume: 0.6, reducedMotion: "thin", sounds: {} }
  sounds.sounds ??= {}
  sounds.$schema ??= schemaUrlFor(registry.url)

  const added = []
  const replaced = []
  const kept = []
  for (const item of chosen) {
    const detail = await fetchItem(registry, item.name)
    const entries = detail.meta?.sounds
    if (!entries || Array.isArray(entries)) {
      fail(`${item.name} has no sound data in the registry; rebuild it with npm run registry:build`)
    }
    for (const [key, entry] of Object.entries(entries)) {
      if (!(key in sounds.sounds)) {
        sounds.sounds[key] = entry
        added.push(key)
      } else if (options.overwrite) {
        sounds.sounds[key] = entry
        replaced.push(key)
      } else {
        kept.push(key)
      }
    }
  }

  const where = relative(CWD, soundsPath) || soundsPath
  console.log(`95-sound-lib: ${chosen.length === 0 ? "no installed UI95 components have sounds" : `checked ${chosen.map((item) => item.name).join(", ")}`}`)
  if (added.length) console.log(`  added ${added.length}: ${added.join(", ")}`)
  if (replaced.length) console.log(`  replaced ${replaced.length}: ${replaced.join(", ")}`)
  if (kept.length) console.log(`  kept ${kept.length} you already have: ${kept.join(", ")}`)
  if (options["dry-run"]) {
    console.log(`  dry run: ${where} not written`)
    return
  }
  if (added.length || replaced.length || !existsSync(soundsPath)) {
    if (!existsSync(dirname(soundsPath))) {
      fail(`folder ${dirname(soundsPath)} does not exist`)
    }
    writeFileSync(soundsPath, `${JSON.stringify(sounds, null, 2)}\n`)
    console.log(`  wrote ${where}`)
  } else {
    console.log(`  ${where} is up to date`)
  }
}

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: {
    overwrite: { type: "boolean" },
    registry: { type: "string" },
    file: { type: "string" },
    "dry-run": { type: "boolean" },
    help: { type: "boolean", short: "h" },
  },
})

const [command, ...names] = positionals
if (values.help || command !== "sync") {
  console.log(USAGE)
  process.exit(values.help ? 0 : 1)
}
await sync(names, values)
```

## Notes

Render <Ui95Sounds /> once in your root layout. Sounds live in sounds.json next to components.json (in src/ if @/* maps to ./src/*). After adding UI95 components run: node scripts/95-sound-lib.mjs sync. It adds only the sounds of installed components and keeps your edits. Silence one element with data-sound="none", rename its sound with data-sound="my-key", silence a sound with "key": false, or everything with "enabled": false.

## API reference

### Ui95Sounds

| Prop | Type | Default |
| --- | --- | --- |
| `config` | `SoundsConfig` | `soundsConfig` |
