diff --git a/src/app/fear/scene-components/ambient-sound.tsx b/src/app/fear/scene-components/ambient-sound.tsx index e6f2bf6..dbb458d 100644 --- a/src/app/fear/scene-components/ambient-sound.tsx +++ b/src/app/fear/scene-components/ambient-sound.tsx @@ -7,13 +7,39 @@ interface AmbientSoundProps { export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) { const audioRef = useRef(null) + const targetVolumeRef = useRef(volume) + + targetVolumeRef.current = volume useEffect(() => { const audio = new Audio(url) audio.loop = true + audio.volume = 0 audioRef.current = audio + let componentsMounted = true + + const attemptPlay = () => { + if (!audioRef.current || !componentsMounted) return + + audio.volume = targetVolumeRef.current + + if (audio.volume > 0 && audio.paused) { + audio.play().catch((err) => { + console.warn('Autoplay management holding clip playback execution.', err) + }) + } + } + + attemptPlay() + + window.addEventListener('click', attemptPlay) + window.addEventListener('keydown', attemptPlay) + return () => { + componentsMounted = false + window.removeEventListener('click', attemptPlay) + window.removeEventListener('keydown', attemptPlay) audio.pause() audio.src = '' audioRef.current = null @@ -24,30 +50,15 @@ export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) { 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) { + if (!audio.paused) audio.pause() + } else { + audio.volume = volume + if (audio.paused) { + audio.play().catch(() => {}) } } - - 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]) + }, [volume]) return null } \ No newline at end of file