Sistema de audio + música de fondo

This commit is contained in:
Nulo 2021-07-06 20:47:00 +00:00
parent 1c66167ce0
commit c51040f680
3 changed files with 32 additions and 8 deletions

View file

@ -29,6 +29,7 @@ import arbol2 from "./assets/Árbol 2.png";
import ciudadanx1 from "./assets/Firma 1.png"; import ciudadanx1 from "./assets/Firma 1.png";
import ciudadanx2 from "./assets/Firma 2.png"; import ciudadanx2 from "./assets/Firma 2.png";
import ciudadanx3 from "./assets/Firma 3.png"; import ciudadanx3 from "./assets/Firma 3.png";
import fondo from "./assets/fondo.ogg";
function loadImage(url: string): Promise<HTMLImageElement> { function loadImage(url: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -38,8 +39,17 @@ function loadImage(url: string): Promise<HTMLImageElement> {
img.src = url; img.src = url;
}); });
} }
function loadAudio(url: string): Promise<HTMLAudioElement> {
return new Promise((resolve, reject) => {
let audio = new Audio();
audio.oncanplaythrough = () => resolve(audio);
audio.onerror = (e) => reject(e);
audio.src = url;
audio.load();
});
}
export const assetUrls = { export const imageAssetUrls = {
botonComenzar, botonComenzar,
botonSiguiente, botonSiguiente,
botonCompartirPerdiste, botonCompartirPerdiste,
@ -72,15 +82,27 @@ export const assetUrls = {
ciudadanx2, ciudadanx2,
ciudadanx3, ciudadanx3,
}; };
export type Assets = { [key in keyof typeof assetUrls]: HTMLImageElement }; export const audioAssetUrls = {
fondo,
};
const assets = Object.fromEntries( export type Assets = {
Object.entries(assetUrls).map(([name, url]) => [name, loadImage(url)]) [key in keyof typeof imageAssetUrls]: HTMLImageElement;
} &
{ [key in keyof typeof audioAssetUrls]: HTMLAudioElement };
const imageAssets = Object.fromEntries(
Object.entries(imageAssetUrls).map(([name, url]) => [name, loadImage(url)])
);
const audioAssets = Object.fromEntries(
Object.entries(audioAssetUrls).map(([name, url]) => [name, loadAudio(url)])
); );
export async function loadAssets() { export async function loadAssets() {
const imgs = await Promise.all(Object.values(assets)); const imgs = await Promise.all(Object.values(imageAssets));
return Object.fromEntries( const audios = await Promise.all(Object.values(audioAssets));
imgs.map((img, i) => [Object.keys(assetUrls)[i], img]) return Object.fromEntries([
) as Assets; ...imgs.map((img, i) => [Object.keys(imageAssetUrls)[i], img]),
...audios.map((audio, i) => [Object.keys(audioAssetUrls)[i], audio]),
]) as Assets;
} }

BIN
src/assets/fondo.ogg Normal file

Binary file not shown.

View file

@ -131,6 +131,8 @@ export function update(juego: Juego<State>, dt: number) {
return; return;
} }
juego.assets.fondo.play();
juego.state.time -= dt; juego.state.time -= dt;
if (juego.state.time < 0) { if (juego.state.time < 0) {
juego.state.has = "lost"; juego.state.has = "lost";