Add audio caching to prevent the browser from imploding

This commit is contained in:
Ketchetwahmeegwun T. Southall 2022-01-30 02:27:32 -08:00
parent f83ddcd81d
commit a4c05bcc16

View File

@ -41,6 +41,8 @@ for (let [key, value] of (Object.entries(audio))) {
audio.src = value audio.src = value
} }
let audioCache: HTMLAudioElement[] = []
let playingSongAudio: HTMLAudioElement let playingSongAudio: HTMLAudioElement
export function playSong(name: string) { export function playSong(name: string) {
if (!enabled) return if (!enabled) return
@ -88,14 +90,23 @@ export function playSong(name: string) {
} }
} }
export function playSound(name: string, volume: number): HTMLAudioElement { export function playSound(name: string, volume: number): HTMLAudioElement|undefined {
let s = new Audio() if (!enabled) return
if (!enabled) return s let s = audioCache.pop()
if (!s) {
s = new Audio()
s.autoplay = true
s.preload = ''
s.addEventListener('ended', () => {
audioCache.push(s as HTMLAudioElement)
})
} else {
console.log('reused')
}
s.src = audio[name] s.src = audio[name]
s.volume = volume s.volume = volume
s.autoplay = true
s.preload = ''
let promise = s.play() let promise = s.play()
if (promise !== undefined) { if (promise !== undefined) {
promise.then(() => { promise.then(() => {