fix: audio handling
This commit is contained in:
@@ -11,31 +11,41 @@ export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const audio = new Audio(url)
|
const audio = new Audio(url)
|
||||||
audio.loop = true
|
audio.loop = true
|
||||||
audio.volume = volume
|
|
||||||
audioRef.current = audio
|
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 () => {
|
return () => {
|
||||||
window.removeEventListener('click', startAudio)
|
|
||||||
window.removeEventListener('keydown', startAudio)
|
|
||||||
audio.pause()
|
audio.pause()
|
||||||
|
audio.src = ''
|
||||||
audioRef.current = null
|
audioRef.current = null
|
||||||
}
|
}
|
||||||
}, [url])
|
}, [url])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (audioRef.current) {
|
const audio = audioRef.current
|
||||||
audioRef.current.volume = volume
|
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])
|
}, [volume])
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user