fix: issue with AmbientSound not updating correctly

This commit is contained in:
2026-06-01 15:37:46 -03:00
parent cb15cc3d95
commit c04d8536c0
+31 -20
View File
@@ -7,13 +7,39 @@ interface AmbientSoundProps {
export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) { export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) {
const audioRef = useRef<HTMLAudioElement | null>(null) const audioRef = useRef<HTMLAudioElement | null>(null)
const targetVolumeRef = useRef<number>(volume)
targetVolumeRef.current = volume
useEffect(() => { useEffect(() => {
const audio = new Audio(url) const audio = new Audio(url)
audio.loop = true audio.loop = true
audio.volume = 0
audioRef.current = audio 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 () => { return () => {
componentsMounted = false
window.removeEventListener('click', attemptPlay)
window.removeEventListener('keydown', attemptPlay)
audio.pause() audio.pause()
audio.src = '' audio.src = ''
audioRef.current = null audioRef.current = null
@@ -24,28 +50,13 @@ export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) {
const audio = audioRef.current const audio = audioRef.current
if (!audio) return 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 (volume === 0) {
audio.pause() if (!audio.paused) audio.pause()
} else { } else {
startAudio() audio.volume = volume
if (audio.paused) {
window.addEventListener('click', startAudio, { once: true }) audio.play().catch(() => {})
window.addEventListener('keydown', startAudio, { once: true }) }
}
return () => {
window.removeEventListener('click', startAudio)
window.removeEventListener('keydown', startAudio)
} }
}, [volume]) }, [volume])