Audio Source Abstraction

by Ehsan Ziya

HTML

<input type="button" id="play" value = "PLAY">

JavaScript

//setting up a loader object
function Sound(source){
    
    //if context has not been created create one
    //if not ignore and do the rest
    if(!window.audioContext){
    context = new webkitAudioContext();
    }
    
    //for later use and avoiding the scope issues
    var that = this;
    that.source = source;
    that.buffer = null;
    //creating a isLoaded property so later we can check
    //if it has been loaded or not
    that.isLoaded = false;
    //loading files to the buffer
    var request = new XMLHttpRequest();
        request.open('GET', source , true);
        request.responseType = "arraybuffer";
    request.onload = function(){
        context.decodeAudioData(request.response, function(buffer){
        that.buffer = buffer;
        that.isLoaded = true;
        });
    };
    request.send();
}
//adding a play method for the sound object
Sound.prototype.play = function(){
    var Seda = context.createBufferSource();
        Seda.buffer = this.buffer;
        Seda.connect(context.destination);
        Seda.start(0);

};

var button = document.getElementById('play');
test = new Sound('http://thelab.thingsinjars.com/web-audio-tutorial/hello.mp3');

test2 = new Sound('http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3');

button.addEventListener('click', function(){
test.play();
test2.play();
});