Open History to see the last commit
1import { useSyncExternalStore } from "react"
2
3const SOUND_KEY = "boxes:sound-enabled"
4let enabled = true
5try {
6 enabled = localStorage.getItem(SOUND_KEY) !== "false"
7} catch {
8 // Sound preferences still work when browser storage is unavailable.
9}
10
11const listeners = new Set<() => void>()
12let context: AudioContext | null = null
13let output: GainNode | null = null
14
15/** Lazily unlock audio from a drawing gesture, respecting browser autoplay rules. */
16function getAudio(): AudioContext | null {
17 if (!enabled || document.hidden || typeof AudioContext === "undefined") return null
18 if (!context) {
19 context = new AudioContext()
20 output = context.createGain()
21 output.gain.value = 0.35
22 output.connect(context.destination)
23 }
24 if (context.state === "suspended") void context.resume().catch(() => {})
25 return context
26}
27
28/** A brief, filtered noise stroke, timed to the pencil's movement along an edge. */
29export function playPencilSound(): void {
30 try {
31 const audio = getAudio()
32 if (!audio) return
33 const duration = 0.16
34 const buffer = audio.createBuffer(1, Math.ceil(audio.sampleRate * duration), audio.sampleRate)
35 const samples = buffer.getChannelData(0)
36 let friction = 0
37 let pressure = 0
38 const frictionBlend = 1 - Math.exp((-2 * Math.PI * 1100) / audio.sampleRate)
39 const pressureBlend = 1 - Math.exp((-2 * Math.PI * 45) / audio.sampleRate)
40 for (let i = 0; i < samples.length; i++) {
41 // Correlated noise gives graphite a dry friction texture rather than a
42 // white-noise hiss. Slower random variations imitate changing pressure.
43 const noise = Math.random() * 2 - 1
44 friction += frictionBlend * (noise - friction)
45 pressure += pressureBlend * (noise - pressure)
46 samples[i] = (friction * 0.9 + noise * 0.08) * (0.7 + Math.min(0.3, Math.abs(pressure) * 3))
47 }
48 const source = audio.createBufferSource()
49 source.buffer = buffer
50 const filter = audio.createBiquadFilter()
51 filter.type = "bandpass"
52 filter.frequency.value = 1200
53 filter.Q.value = 0.5
54 const gain = audio.createGain()
55 const start = audio.currentTime + 0.04
56 // Swell through the stroke, then ease off as the pencil lifts. The longer
57 // attack and release make changing pressure audible rather than a flat hiss.
58 gain.gain.setValueAtTime(0, start)
59 gain.gain.linearRampToValueAtTime(0.9, start + 0.065)
60 gain.gain.linearRampToValueAtTime(0, start + duration)
61 source.connect(filter).connect(gain).connect(output!)
62 source.onended = () => {
63 source.disconnect()
64 filter.disconnect()
65 gain.disconnect()
66 }
67 source.start(start)
68 } catch {
69 // Audio is optional; a device or browser audio failure must never block a move.
70 }
71}
72
73/** Reward only the player's server-confirmed claims, with an extra note for two boxes. */
74export function playBoxSound(boxes: number): void {
75 if (boxes <= 0) return
76 try {
77 const audio = getAudio()
78 if (!audio) return
79 const notes = boxes > 1 ? [784, 1046.5, 1318.5, 1568] : [784, 1046.5, 1318.5]
80 notes.forEach((frequency, index) => {
81 const start = audio.currentTime + index * 0.07
82 const oscillator = audio.createOscillator()
83 oscillator.type = "sine"
84 oscillator.frequency.value = frequency
85 const gain = audio.createGain()
86 gain.gain.setValueAtTime(0, start)
87 gain.gain.linearRampToValueAtTime(0.22, start + 0.008)
88 gain.gain.exponentialRampToValueAtTime(0.001, start + 0.2)
89 oscillator.connect(gain).connect(output!)
90 oscillator.onended = () => {
91 oscillator.disconnect()
92 gain.disconnect()
93 }
94 oscillator.start(start)
95 oscillator.stop(start + 0.21)
96 })
97 } catch {
98 // Keep successful moves independent of audio availability.
99 }
100}
101
102function toggleSound(): void {
103 enabled = !enabled
104 // Silence already scheduled notes immediately when muting.
105 if (context && output) output.gain.setValueAtTime(enabled ? 0.35 : 0, context.currentTime)
106 try {
107 localStorage.setItem(SOUND_KEY, String(enabled))
108 } catch {
109 // The current session can still be muted without persistence.
110 }
111 for (const listener of listeners) listener()
112}
113
114const subscribe = (listener: () => void) => {
115 listeners.add(listener)
116 return () => {
117 listeners.delete(listener)
118 }
119}
120
121export function useGameSoundPreference() {
122 const soundEnabled = useSyncExternalStore(subscribe, () => enabled)
123 return { soundEnabled, toggleSound }
124}