fix: issue with AmbientSound not updating correctly
This commit is contained in:
@@ -7,13 +7,39 @@ interface AmbientSoundProps {
|
||||
|
||||
export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) {
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const targetVolumeRef = useRef<number>(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,28 +50,13 @@ 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) {
|
||||
audio.pause()
|
||||
if (!audio.paused) audio.pause()
|
||||
} else {
|
||||
startAudio()
|
||||
|
||||
window.addEventListener('click', startAudio, { once: true })
|
||||
window.addEventListener('keydown', startAudio, { once: true })
|
||||
audio.volume = volume
|
||||
if (audio.paused) {
|
||||
audio.play().catch(() => {})
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('click', startAudio)
|
||||
window.removeEventListener('keydown', startAudio)
|
||||
}
|
||||
}, [volume])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user