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);
function Sound(source){
var that = this;
that.source = source;
that.buffer = null;
that.isLoaded = false;
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();
this.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);
};
this.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(context.destination,true,1,0.1);
});
button2.addEventListener('click', function(){
test.stop();
});