Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Created May 12, 2014 07:45
Show Gist options
  • Save jussi-kalliokoski/4e50f671d6796add4ce5 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/4e50f671d6796add4ce5 to your computer and use it in GitHub Desktop.
Web Audio Worker Example - Shared Parallel
let context = new AudioContext();
let noiseWorker = context.createAudioWorker("worker.js");
let noiseNode1 = context.createScriptProcessor(noiseWorker);
let noiseNode2 = context.createScriptProcessor(noiseWorker);
let oscillator = context.createOscillator();
noiseNode1.connect(oscillator.detune);
noiseNode2.connect(context.destination);
oscillator.connect(context.destination);
oscillator.start(context.currentTime);
this.onmessage = function (event) {
if ( !event.data || event.data.type !== "fillBuffer" ) {
return;
}
let buffer = new Float32Array(event.data.length);
for ( let i = 0; i < buffer.length; i++ ) {
buffer[i] = Math.random() * 2 - 1;
}
this.postMessage({
type: "buffer",
buffer: buffer
});
};
let fillQueue = [];
let workerPool = [0, 1, 2, 3].map(function () {
let worker = new Worker("subworker.js");
worker.onmessage = function (event) {
if ( !event.data || event.data.type !== "buffer" ) {
return;
}
fillQueue.shift(event.data.buffer);
};
return worker;
});
let workerPoolIndex = 0;
let queueFill = function (size, callback) {
let worker = workerPool[workerPoolIndex];
workerPoolIndex = (workerPoolIndex + 1) % workerPool.length;
fillQueue.push(callback);
worker.postMessage({
type: "fillBuffer",
size: size
});
};
let fillBuffer = function (buffer) {
let deferred = Promise.defer();
queueFill(buffer.length, function (filledBuffer) {
buffer.set(filledBuffer);
deferred.resolve();
});
return deferred.promise;
};
this.onaudioprocess = function (event) {
let buffers = event.data.channels;
return Promise.all(buffers.map(fillBuffer)).then(function () {
event.finish();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment