ridder
Version:
A straightforward game engine for simple data-driven games in JavaScript
72 lines (71 loc) • 2.26 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const sounds = [];
let volume = 1;
/**
* Load a sound into the cache.
* @param id - The ID for the sound in the cache.
* @param url - The url to the `.mp3`, `.wav`, or `.ogg` file.
* @param stream - Whether or not the sound should be streamed, e.g. for large files such as music.
*/
export function loadSound(id_1, url_1) {
return __awaiter(this, arguments, void 0, function* (id, url, stream = false) {
return yield new Promise((resolve, reject) => {
const audio = new Audio(url);
const event = stream ? "canplay" : "canplaythrough";
audio.addEventListener(event, () => {
sounds[id] = audio;
resolve();
}, { once: true });
audio.addEventListener("error", (e) => {
reject(e);
}, { once: true });
});
});
}
/**
* Play a sound from the cache.
*/
export function playSound(id, loop = false) {
const sound = sounds[id];
sound.loop = loop;
sound.volume = volume;
sound.play();
}
/**
* Stop a currently playing sound.
*/
export function stopSound(id) {
const sound = sounds[id];
sound.pause();
sound.currentTime = 0;
}
/**
* Get a sound from the cache.
*/
export function getSound(id) {
return sounds[id];
}
/**
* Set the global audio volume.
*/
export function setVolume(value) {
volume = value;
for (const id in sounds) {
const sound = sounds[id];
sound.volume = volume;
}
}
/**
* Get the global audio volume.
*/
export function getVolume() {
return volume;
}