1
0
Fork 0
soundbox/soundbox.js

50 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-07-31 17:57:55 +00:00
/**
* SoundBox
* By Starbeamrainbowlabs
* A super simple JS library for playing sound effects and other audio.
*
* Note to self: When making a release, remember to update the version number at the bottom of the file!
*/
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 18:14:28 +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") {
soundInstance.addEventListener("ended", callback);
return true;
}
else {
return new Promise((resolve, reject) => soundInstance.addEventListener("ended", resolve));
}
2015-02-17 10:12:05 +00:00
};
}
2017-07-31 17:57:55 +00:00
2017-07-31 18:27:33 +00:00
SoundBox.version = "0.2.2";