From e6e29440563e33bb67e0ad51f9fb6c5c2c3fe809 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Thu, 7 Mar 2024 20:45:47 -0700 Subject: level one (applications prototype finished!) --- src/engine/config/assets.ts | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) (limited to 'src/engine/config/assets.ts') 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(); +export const SOUNDS = new Map(); export const loadSpritesIntoImageElements = ( spriteSpecs: Partial[], @@ -35,6 +37,45 @@ export const loadSpritesIntoImageElements = ( return spritePromises; }; +export const loadSoundsIntoAudioElements = ( + soundSpecs: SoundSpec[], +): Promise[] => { + const soundPromises: Promise[] = []; + + 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((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())), ]); -- cgit v1.2.3-70-g09d2