I'm trying to get the following code to work. I trigger the sound with arrow left, and I want it to keep playing until I release the key. I'm having a bit of a problem finding out what the scope of each sound has, so I can send it a stop or .pause command.
window.AudioContext = window.AudioContext || window.webkitAudioContext;
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function (url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function () {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function (buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length) loader.onload(loader.bufferList);
},
function (error) {
console.error('decodeAudioData error', error);
});
}
request.onerror = function (e) {
alert('BufferLoader: XHR error');
console.log(e);
}
request.send();
}
BufferLoader.prototype.load = function () {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
/// setup audio context and start loading samples
var actx = new AudioContext(),
blst,
bLoader = new BufferLoader(
actx, [
'http://ift.tt/1fBE5e1',
'http://ift.tt/1WOAafM',
'http://ift.tt/1fBE6yu'],
done),
isReady = false;
/// start loading the samples
bLoader.load();
/// when samples are loaded update status
function done(bl) {
blst = bl;
isReady = true;
$('#status').html('Ready!');
}
/// this sets up chain so we can play audio
function play(i) {
var src = actx.createBufferSource();
src.buffer = blst[i];
src.connect(actx.destination);
//src.loop = true;
src.start(0);
playing = i;
var output = '';
for (var property in actx) {
output += property + ': ' + actx[property]+'; ';
}
console.log(output);
}
function stop(i) {
//src.stop(context.currentTime);
//src.stop(i);
console.log("stop " + i);
}
/// check keys
var arrowKeyDown = false;
$('body').keydown(function(e) {
if (e.which == 37 && !arrowKeyDown) {
arrowKeyDown = true;
play(0);
// ...
}
});
$('body').keyup(function(e) {
if (e.which == 37) {
arrowKeyDown = false;
stop(0);
}
});
$(window).bind("keydown", function (key) {
if (!isReady) return;
var output = '';
for (var property in key) {
output += property + ': ' + key[property]+'; ';
}
//console.log(output);
switch (parseInt(key.which, 10)) {
case 65:
play(0);
break;
case 83:
play(1);
break;
case 68:
play(2);
break;
}
})
$(window).bind("keyup", function (key) {
if (!isReady) return;
switch (parseInt(key.which, 10)) {
case 65:
stop(0);
break;
case 83:
stop(1);
break;
case 68:
stop(2);
break;
}
})
Aucun commentaire:
Enregistrer un commentaire