GGJ22/Engine/src/shared/audio.ts

103 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-01-29 19:41:18 -08:00
import assets from 'url:../../../Assets/Audio/**/*.ogg'
2022-01-30 01:01:18 -08:00
console.log('audio assets:', assets)
2022-01-29 19:41:18 -08:00
2022-01-30 01:01:18 -08:00
type Entry = { [key: string]: string | Entry }
export const audio: Record<string, string> = {}
function traverse(path: string, entry: Entry|string) {
if (typeof entry === 'string') {
audio[path] = entry
} else if (typeof entry === 'object') {
for (let [key, value] of Object.entries(entry)) {
traverse((path?path+'/':'')+key, value)
}
}
}
traverse('', assets)
2022-01-29 19:41:18 -08:00
2022-01-29 19:46:06 -08:00
export let enabled = true
export function enableSound() {
enabled = true
if (playingSongAudio) {
playingSongAudio.play()
}
}
export function disableSound() {
enabled = false
if (playingSongAudio) {
playingSongAudio.pause()
}
}
2022-01-29 19:41:18 -08:00
// Preload 'em
2022-01-30 01:01:18 -08:00
for (let [key, value] of (Object.entries(audio))) {
2022-01-29 19:41:18 -08:00
let audio = new Audio()
audio.addEventListener('canplaythrough', () => {
console.log('preloaded audio', key)
})
audio.preload = ''
audio.src = value
}
let playingSongAudio: HTMLAudioElement
export function playSong(name: string) {
2022-01-29 19:46:06 -08:00
if (!enabled) return
2022-01-29 19:41:18 -08:00
// Replace old audio and start crossfading.
if (playingSongAudio && !playingSongAudio.paused) {
;((playingSongAudio: HTMLAudioElement) => {
let cl = setInterval(() => {
if (Number(playingSongAudio.volume.toFixed(1)) > 0) {
playingSongAudio.volume -= 0.1
} else {
clearInterval(cl)
}
2022-01-29 20:01:10 -08:00
}, 50)
2022-01-29 19:41:18 -08:00
})(playingSongAudio)
}
playingSongAudio = new Audio()
playingSongAudio.autoplay = true
playingSongAudio.preload = ''
playingSongAudio.loop = true
playingSongAudio.volume = 0
// Start fade in.
;((playingSongAudio: HTMLAudioElement) => {
let cl = setInterval(() => {
if (playingSongAudio.paused) {
clearInterval(cl)
return
}
if (Number(playingSongAudio.volume.toFixed(1)) < 1.0) {
playingSongAudio.volume += 0.1
} else {
clearInterval(cl)
}
2022-01-29 20:01:10 -08:00
}, 50)
2022-01-29 19:41:18 -08:00
})(playingSongAudio)
playingSongAudio.src = audio[name]
let promise = playingSongAudio.play()
if (promise !== undefined) {
promise.then(() => {
// ok
}).catch((error: any) => {
//console.error(error)
})
}
}
export function playSound(name: string): HTMLAudioElement {
let s = new Audio()
2022-01-29 19:46:06 -08:00
if (!enabled) return s
2022-01-29 19:41:18 -08:00
s.src = audio[name]
s.autoplay = true
s.preload = ''
;(async () => {
await s.play()
})()
return s
}