Skip to content

Instantly share code, notes, and snippets.

Created November 15, 2013 21:29
Show Gist options
  • Save anonymous/7491945 to your computer and use it in GitHub Desktop.
Save anonymous/7491945 to your computer and use it in GitHub Desktop.
function AudioWrapper(src){//Simple audio wrapper
var audio = new Audio(), self = this;//create the audio element
audio.src = src;//set the source...
['play','stop','pause'].forEach(function(item){//play stop and pause hookup
var actualCommand = item === 'stop'?'pause':item;//when stopping, use pause instead
self[item] = function(){//set the function...
audio[actualCommand]();//call the pause or play function
if(item === 'stop')//and if stop is called...
self.currentTime(0);//go back to the start
};
});
this.currentTime = function(time){//small convenience function
return audio.currentTime=time||src.currentTime;//sets the current time or returns it
};
this.canPlay = function(){//just checks to see if the readyState is 4
return audio.readyState === 4;//ready state!
};
this.onReady = function(func){//Any function hooked here will be called 100% of the time
var args = [].slice.call(arguments, 1);//unless it isn't loaded
function checkReady(){//named function
if(self.canPlay())//check to see if it can be played
func.apply(self, args);//call the function...
else
setTimeout(checkReady,100);//check in a few seconds.
}
checkReady();//start up!
};
}
var x = new AudioWrapper(src);//create the Audio
x.onReady(function(playLength){//hook up a function...
x.play();
setTimeout(x.stop, playLength);
},10000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment