Skip to content

Instantly share code, notes, and snippets.

@Olical
Created September 11, 2011 10:09
Show Gist options
  • Select an option

  • Save Olical/1209420 to your computer and use it in GitHub Desktop.

Select an option

Save Olical/1209420 to your computer and use it in GitHub Desktop.
JavaScript Sound class
var mySound = new Sound('http://wolfy87.github.com/NyanTunnel/assets/audio/nyan-cat.ogg', function() {
this.play();
});
mySound.set('volume', 0.1);
var duration = mySound.get('duration');
function Sound(file, callback) {
var instance = this;
instance.element = new Audio();
instance.loaded = false;
instance.get = function(property) {
return instance.element[property];
};
instance.set = function(property, value) {
instance.element[property] = value;
};
instance.play = function() {
instance.element.play();
};
instance.pause = function() {
instance.element.pause();
};
instance.stop = function() {
instance.pause();
instance.setTime(0);
};
instance.load = function(file, callback) {
instance.loaded = false;
var loadedHandler = function() {
instance.loaded = true;
instance.element.removeEventListener('canplaythrough', loadedHandler);
if(callback) {
callback.apply(instance);
}
};
instance.element.addEventListener('canplaythrough', loadedHandler);
instance.element.set('src', file);
instance.element.load();
};
if(file) {
instance.load(file, callback);
}
}
function Sound(b,e){var a=this;a.element=new Audio;a.loaded=!1;a.get=function(c){return a.element[c]};a.set=function(c,d){a.element[c]=d};a.play=function(){a.element.play()};a.pause=function(){a.element.pause()};a.stop=function(){a.pause();a.setTime(0)};a.load=function(c,d){a.loaded=!1;var b=function(){a.loaded=!0;a.element.removeEventListener("canplaythrough",b);d&&d.apply(a)};a.element.addEventListener("canplaythrough",b);a.element.set("src",c);a.element.load()};b&&a.load(b,e)};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment