Created
September 8, 2025 17:07
-
-
Save aghyad97/1005b5891ae9f88e6bc7de699a3f3799 to your computer and use it in GitHub Desktop.
Playing sounds with Web APIs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const audioCtxRef = useRef<AudioContext | null>(null); | |
| const ensureAudio = useCallback(() => { | |
| if (audioCtxRef.current) return audioCtxRef.current; | |
| const Ctx = | |
| (window as any).AudioContext || (window as any).webkitAudioContext; | |
| if (!Ctx) return null; | |
| audioCtxRef.current = new Ctx(); | |
| return audioCtxRef.current; | |
| }, []); | |
| const playClick = useCallback(() => { | |
| if (!soundEnabled) return; | |
| const ctx = ensureAudio(); | |
| if (!ctx) return; | |
| try { | |
| const osc = ctx.createOscillator(); | |
| const gain = ctx.createGain(); | |
| // mechanical-like click: short noise burst + high-pitched blip layered | |
| osc.type = "square"; | |
| osc.frequency.value = 3200; | |
| const now = ctx.currentTime; | |
| gain.gain.setValueAtTime(0.0001, now); | |
| gain.gain.exponentialRampToValueAtTime(0.3, now + 0.005); | |
| gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.06); | |
| osc.connect(gain); | |
| gain.connect(ctx.destination); | |
| osc.start(now); | |
| osc.stop(now + 0.07); | |
| // subtle lower thock | |
| const osc2 = ctx.createOscillator(); | |
| const gain2 = ctx.createGain(); | |
| osc2.type = "triangle"; | |
| osc2.frequency.value = 180; | |
| gain2.gain.setValueAtTime(0.0001, now); | |
| gain2.gain.exponentialRampToValueAtTime(0.08, now + 0.003); | |
| gain2.gain.exponentialRampToValueAtTime(0.0001, now + 0.05); | |
| osc2.connect(gain2); | |
| gain2.connect(ctx.destination); | |
| osc2.start(now); | |
| osc2.stop(now + 0.06); | |
| } catch (_e) {} | |
| }, [ensureAudio, soundEnabled]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment