fix: prevent multiple simultaneous sound plays

This commit is contained in:
CHaBou 2025-10-18 14:50:11 +02:00
parent a071ba04c7
commit 4445a01e6b

View file

@ -30,6 +30,7 @@ export function useSound(
html5: boolean = false,
) {
const [hasLoaded, setHasLoaded] = useState(false);
const [isPlaying, setIsPlaying] = useState(false);
const isLoading = useLoadingStore(state => state.loaders[src]);
const setIsLoading = useLoadingStore(state => state.set);
@ -40,6 +41,11 @@ export function useSound(
if (isBrowser) {
sound = new Howl({
html5,
onend: () => {
if (!options.loop) {
setIsPlaying(false);
}
},
onload: () => {
setIsLoading(src, false);
setHasLoaded(true);
@ -50,7 +56,7 @@ export function useSound(
}
return sound;
}, [src, isBrowser, setIsLoading, html5, options.preload]);
}, [src, isBrowser, setIsLoading, html5, options.preload, options.loop]);
useEffect(() => {
if (sound) {
@ -70,22 +76,25 @@ export function useSound(
sound.load();
}
if (!sound.playing()) {
if (!isPlaying) {
setIsPlaying(true);
sound.play();
}
if (typeof cb === 'function') sound.once('end', cb);
}
},
[src, setIsLoading, sound, hasLoaded, isLoading],
[src, setIsLoading, sound, hasLoaded, isLoading, isPlaying],
);
const stop = useCallback(() => {
if (sound) sound.stop();
setIsPlaying(false);
sound?.stop();
}, [sound]);
const pause = useCallback(() => {
if (sound) sound.pause();
setIsPlaying(false);
sound?.pause();
}, [sound]);
const fadeOut = useCallback(