Added more SFX logic

This commit is contained in:
2025-02-06 21:43:09 +01:00
parent 6383320e8c
commit 12735756d7
5 changed files with 47 additions and 5 deletions

View File

@ -1,10 +1,40 @@
export function useGameComposable() {
const playSound = (sound: string) => {
const activeSounds: { [key: string]: HTMLAudioElement } = {}
const playSound = (sound: string, loop: boolean = false, ignoreIfPlaying: boolean = false) => {
// If sound is already playing and we want to ignore
if (ignoreIfPlaying && activeSounds[sound] && !activeSounds[sound].paused) {
return
}
// Stop previous instance of this sound if it exists
if (activeSounds[sound]) {
activeSounds[sound].pause()
activeSounds[sound].currentTime = 0
}
const audio = new Audio(sound)
audio.loop = loop
// Store reference to track playing state
activeSounds[sound] = audio
audio.addEventListener('ended', () => {
delete activeSounds[sound]
})
audio.play().catch(console.error)
}
const stopSound = (sound: string) => {
if (!activeSounds[sound]) return
activeSounds[sound].pause()
activeSounds[sound].currentTime = 0
delete activeSounds[sound]
}
return {
playSound
playSound,
stopSound
}
}