Skip to content

Instantly share code, notes, and snippets.

@walmik
Created February 27, 2018 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walmik/e8e21ca87ccc92d5b70495db888dadab to your computer and use it in GitHub Desktop.
Save walmik/e8e21ca87ccc92d5b70495db888dadab to your computer and use it in GitHub Desktop.
Code snippet to load a couple of wave files (from disc) and play em in a sequence
window.onload = init;
var context;
var bufferLoader;
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() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
function init() {
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
bufferLoader = new BufferLoader(
context,
[
'techno-kit1.wav',
'Bass09.wav',
],
finishedLoading
);
bufferLoader.load();
}
function playSound(buffer, time) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(time);
}
function finishedLoading(bufferList) {
// Create two sources and play them both together.
var kick = context.createBufferSource();
var bass = context.createBufferSource();
kick = bufferList[0];
bass = bufferList[1];
var eighthNoteTime = 1/8;
var startTime = 0;
for (var bar = 0; bar < 2; bar++) {
var time = startTime + bar * 8 * eighthNoteTime;
// Play the bass (kick) drum on beats 1, 5
playSound(kick, time);
playSound(kick, time + 4 * eighthNoteTime);
// Play the bass drum on beats 3, 7
playSound(bass, time + 2 * eighthNoteTime);
playSound(bass, time + 6 * eighthNoteTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment