[demo] ( https://mikealbo.github.io/webAudioDemo/)
This demo handles the importing and decoding of the audio files passed to it. The demo also includes a playback function. The WebAudio AudioContext is not supported in IE as of yet.
[The W3 standard] (https://www.w3.org/TR/webaudio/#AudioContext-section)
[html5 rocks version of a buffer loader] (https://www.html5rocks.com/en/tutorials/webaudio/intro/js/buffer-loader.js)
loads the init function when the document is ready
window.addEventListener('load', init, false);
init function sets the window.AudioContext, if not supported alerts the user of error. Note: webKit requires "webkitAudioContext".
function init(){
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
console.log("AudioContext created!");
}
catch(e) {
alert("Web Audio not supported in your browser, please try a newer release of Safari, Chrome, or Firefox");
}
}
creates a new instance of AudioLoadBuffer and calls the loadData function()
var newAudio = new AudioLoadBuffer(audioSources);
newAudio.loadData();
audioSources, is a JS object that contains the link to the audio file to be imported.
var audioSources = {
exSound1: {
webLink : 'audioFiles/simonSound1.mp3'
},
exSound2: {
webLink : 'audioFiles/simonSound2.mp3'
}
}
This is also the var the the buffer outputs to and is used in playback.
var audioSources = {
exSound1: {
webLink : 'audioFiles/simonSound1.mp3',
playback: AudioBuffer
},
exSound2: {
webLink : 'audioFiles/simonSound2.mp3',
playback: AudioBuffer
}
}
A constructor that, takes the audioSourc file and calls the XMLHttpRequest() on each object. Upon success, the response is added to the audioSource file.
this.loadData = function(){
for(var file in source){
httpReq(file);
}
function httpReq(file){
//console.log(url);
var request = new XMLHttpRequest();
request.open('GET', source[file].webLink, true);
request.responseType = 'arraybuffer';
request.onload = function(){
context.decodeAudioData(request.response, function(res){
audioSources[file].playback = res;
});
}
request.send();
}
Note : You may encounter access issues if the you are not connecting to your server.
The playback function builds the buffer, conects to the speakers, and starts (plays) the file.
function playBack(buffer){
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
- playSound - switch function, that calls playBack
- button event listeners, call playSound and passes argument
- extract the main functionality into reusable code
- imporve error handling