feat: add AmbientSound component
This commit is contained in:
@@ -0,0 +1,43 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
interface AmbientSoundProps {
|
||||||
|
url: string
|
||||||
|
volume?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AmbientSound({ url, volume = 0.5 }: AmbientSoundProps) {
|
||||||
|
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||||
|
|
||||||
|
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()
|
||||||
|
audioRef.current = null
|
||||||
|
}
|
||||||
|
}, [url])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (audioRef.current) {
|
||||||
|
audioRef.current.volume = volume
|
||||||
|
}
|
||||||
|
}, [volume])
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user