diff options
Diffstat (limited to 'src/engine/config/assets.ts')
-rw-r--r-- | src/engine/config/assets.ts | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/src/engine/config/assets.ts b/src/engine/config/assets.ts index 5ce13e8..fbfab2f 100644 --- a/src/engine/config/assets.ts +++ b/src/engine/config/assets.ts @@ -1,4 +1,5 @@ import { type SpriteSpec, SPRITE_SPECS } from "."; +import { SOUND_SPECS, SoundSpec } from "./sounds"; export const FONT = new FontFace("scientifica", "url(/fonts/scientifica.ttf)"); FONT.load().then((font) => { @@ -6,6 +7,7 @@ FONT.load().then((font) => { }); export const IMAGES = new Map<string, HTMLImageElement>(); +export const SOUNDS = new Map<string, HTMLAudioElement>(); export const loadSpritesIntoImageElements = ( spriteSpecs: Partial<SpriteSpec>[], @@ -35,6 +37,45 @@ export const loadSpritesIntoImageElements = ( return spritePromises; }; +export const loadSoundsIntoAudioElements = ( + soundSpecs: SoundSpec[], +): Promise<void>[] => { + const soundPromises: Promise<void>[] = []; + + for (const soundSpec of soundSpecs) { + if (soundSpec.url) { + const promise = fetch(soundSpec.url) + .then((response) => response.blob()) + .then((blob) => { + const audio = new Audio(); + audio.src = URL.createObjectURL(blob); + audio.volume = soundSpec.volume ?? 1; + + SOUNDS.set(soundSpec.name, audio); + return new Promise<void>((resolve, rej) => { + audio.oncanplaythrough = () => { + resolve(); + }; + + audio.onerror = (e) => { + console.error(soundSpec); + rej(e); + }; + }); + }); + soundPromises.push(promise); + } + + if (soundSpec.states) { + soundPromises.push( + ...loadSoundsIntoAudioElements(Array.from(soundSpec.states.values())), + ); + } + } + + return soundPromises; +}; + export const loadAssets = () => Promise.all([ ...loadSpritesIntoImageElements( @@ -43,5 +84,5 @@ export const loadAssets = () => ), ), FONT.load(), - // TODO: Sound + ...loadSoundsIntoAudioElements(Array.from(SOUND_SPECS.values())), ]); |