client/src/composables/useGameComposable.ts

41 lines
1.0 KiB
TypeScript

export function useGameComposable() {
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,
stopSound
}
}