Audio Source Abstraction Trying to make it modular

by Ehsan Ziya

HTML

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

JavaScript

context = new webkitAudioContext();

mastergain = context.createGainNode();
mastergain.gain.value = 0.9;
mastergain.connect(context.destination);
//setting up a loader object
//looks like this var test = new Sound(url);
//test.play(destination , loop true or false, playback rate)
function Sound(source){

    //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(destination, loop, speed, gain){
    this.sound = context.createBufferSource();
    this.soundGain = context.createGainNode();
    this.sound.buffer = this.buffer;
    this.destination = destination;
    this.speed = speed;
    this.gain = gain;
    this.sound.loop = loop;
    this.sound.playbackRate.value = speed;
     
    this.soundGain.gain.value = gain;
    this.sound.connect(this.soundGain);
    this.soundGain.connect(destination);
    this.sound.start(0);
        

};
//adding a stop method
Sound.prototype.stop = function(){
    this.sound.stop(0);
};














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

button.addEventListener('click', function(){
test.play(mastergain,true,1,0.1);
});

button2.addEventListener('click', function(){
test.stop();
});