1
0
Fork 0
soundbox/soundbox.js

39 lines
1.1 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
return new Promise((resolve, reject) => this.sounds[sound_name].addEventListener("canplaythrough", resolve));
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
};
}