Created
May 12, 2014 07:45
-
-
Save jussi-kalliokoski/4e50f671d6796add4ce5 to your computer and use it in GitHub Desktop.
Web Audio Worker Example - Shared Parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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