How can I assign the buffer created in decodeAudioData to soundBuffer for playback later?
Note the call to playSound() within the decodeAudioData function call plays the buffer successfully, but calls from the Play button return "value not of type ArrayBuffer" and when tested, soundBuffer is still undefined.
I'm assuming the deeply nested function has lost scope to soundBuffer in the outermost function, but I can seem to wrap soundBuffer in a closure such that it is passed in successfully.
$(function () {
var soundBuffer, context;
try {
context = new webkitAudioContext();
}
catch (e) {
console.log("Error setting up webaudiocontext: " + e);
}
loadSound("https://dl.dropboxusercontent.com/u/9780255/counting-coins-3.mp3",soundBuffer);
$("#playSound").click(function () {
playSound(soundBuffer);
});
function loadSound(url, buffer) {
var rq = new XMLHttpRequest();
rq.open("GET", url, true);
rq.responseType = "arraybuffer";
rq.onload = function () {
context.decodeAudioData(rq.response,
function (b) {
buffer = b;
console.log("buffer loaded...");
playSound(buffer);
});
};
rq.onerror = function (e) {
console.log("error loading audio:"+e);
};
rq.send();
}
function playSound(s) {
var sn= context.createBufferSource();
sn.buffer = s;
sn.connect(context.destination);
sn.start(0);
}
});
This source is on jsfiddle: http://jsfiddle.net/karasutengu/qA5Nb/8/ It will likely only work with chrome which recognizes webkitAudioContext.