From fe686b0071da8bd6552ae4801e111dfd680aadfe Mon Sep 17 00:00:00 2001 From: neru Date: Sun, 31 May 2026 22:03:52 -0300 Subject: [PATCH] fix: audio handling --- .../fear/scene-components/ambient-sound.tsx | 42 ++++++++++++------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/src/app/fear/scene-components/ambient-sound.tsx b/src/app/fear/scene-components/ambient-sound.tsx index 27e9b2f..e6f2bf6 100644 --- a/src/app/fear/scene-components/ambient-sound.tsx +++ b/src/app/fear/scene-components/ambient-sound.tsx @@ -11,31 +11,41 @@ export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) { useEffect(() => { const audio = new Audio(url) audio.loop = true - audio.volume = volume audioRef.current = audio - const startAudio = () => { - audio.play().catch((err) => { - console.warn('Autoplay blocked. Waiting for user interaction.', err) - }) - } - - startAudio() - - window.addEventListener('click', startAudio, { once: true }) - window.addEventListener('keydown', startAudio, { once: true }) - return () => { - window.removeEventListener('click', startAudio) - window.removeEventListener('keydown', startAudio) audio.pause() + audio.src = '' audioRef.current = null } }, [url]) useEffect(() => { - if (audioRef.current) { - audioRef.current.volume = volume + const audio = audioRef.current + if (!audio) return + + audio.volume = volume + + const startAudio = () => { + if (audio.volume > 0) { + audio.play().catch((err) => { + console.warn('Autoplay blocked. Waiting for user interaction.', err) + }) + } + } + + if (volume === 0) { + audio.pause() + } else { + startAudio() + + window.addEventListener('click', startAudio, { once: true }) + window.addEventListener('keydown', startAudio, { once: true }) + } + + return () => { + window.removeEventListener('click', startAudio) + window.removeEventListener('keydown', startAudio) } }, [volume])