|
|
import { useSound } from "use-sound"; |
|
|
import { useState, useEffect } from "react"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function useSoundEffect({ |
|
|
basePath, |
|
|
numSounds, |
|
|
volume = 0.5, |
|
|
interrupt = true, |
|
|
enabled = true, |
|
|
}) { |
|
|
const [soundsLoaded, setSoundsLoaded] = useState(false); |
|
|
|
|
|
|
|
|
const soundPaths = Array.from( |
|
|
{ length: numSounds }, |
|
|
(_, i) => `${basePath}${i + 1}.mp3` |
|
|
); |
|
|
|
|
|
|
|
|
const sounds = soundPaths.map((soundPath) => { |
|
|
const [play, { sound }] = useSound(soundPath, { |
|
|
volume, |
|
|
interrupt, |
|
|
}); |
|
|
return { play, sound }; |
|
|
}); |
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
const checkSoundsLoaded = () => { |
|
|
const allSoundsLoaded = sounds.every( |
|
|
({ sound }) => sound && sound.state() === "loaded" |
|
|
); |
|
|
if (allSoundsLoaded) { |
|
|
setSoundsLoaded(true); |
|
|
} |
|
|
}; |
|
|
|
|
|
const interval = setInterval(checkSoundsLoaded, 100); |
|
|
return () => clearInterval(interval); |
|
|
}, [sounds]); |
|
|
|
|
|
|
|
|
const playRandomSound = () => { |
|
|
if (!enabled || !soundsLoaded || sounds.length === 0) { |
|
|
return; |
|
|
} |
|
|
|
|
|
const randomIndex = Math.floor(Math.random() * sounds.length); |
|
|
try { |
|
|
sounds[randomIndex].play(); |
|
|
} catch (error) { |
|
|
console.error("Error playing sound:", error); |
|
|
} |
|
|
}; |
|
|
|
|
|
return playRandomSound; |
|
|
} |
|
|
|