1
0
Fork 0
mirror of https://github.com/sbrl/soundbox.git synced 2018-01-10 21:33:43 +00:00
soundbox/soundbox.js

39 lines
1.2 KiB
JavaScript
Raw Normal View History

2015-02-17 10:14:29 +00:00
function SoundBox() {
2015-02-17 10:12:05 +00:00
this.sounds = {};
this.load = function(sound_name, path, callback) {
2015-02-17 10:12:05 +00:00
this.sounds[sound_name] = new Audio(path);
if(typeof callback == "function")
this.sounds[sound_name].addEventListener("canplaythrough", callback);
else
2017-07-31 17:53:56 +00:00
return new Promise((resolve, reject) => this.sounds[sound_name].addEventListener("canplaythrough", resolve), this.sounds[sound_name].addEventListener("error", reject));
2015-02-17 10:12:05 +00:00
};
2015-02-17 10:14:29 +00:00
this.remove = function(sound_name) {
2015-02-17 10:12:05 +00:00
if(typeof this.sounds != "undefined")
delete this.sounds[sound_name];
if(typeof this.sound_callbacks == "function")
delete this.sound_callbacks[sound_name];
};
2015-02-17 10:14:29 +00:00
this.play = function(sound_name, callback) {
if(typeof this.sounds[sound_name] == "undefined") {
2015-02-17 10:12:05 +00:00
console.error("Can't find sound called '" + sound_name + "'.");
return false;
}
var soundInstance = this.sounds[sound_name].cloneNode(true);
soundInstance.play();
2015-02-17 10:12:05 +00:00
if(typeof callback == "function") {
console.log("Adding callback");
soundInstance.addEventListener("ended", callback);
return true;
}
else {
console.log("Returning promise");
return new Promise((resolve, reject) => soundInstance.addEventListener("ended", resolve));
}
2015-02-17 10:12:05 +00:00
};
}