Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Last active August 29, 2015 14:06
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 jussi-kalliokoski/4ac8d1452fd837cd50b6 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/4ac8d1452fd837cd50b6 to your computer and use it in GitHub Desktop.
Multiple different nodes on the same worker
var context = new AudioContext();
var audioWorker = context.createAudioWorker("worker.js");
var sine = context.createAudioWorkerNode(audioWorker, {
numberOfInputChannels: 0,
numberOfOutputChannels: 1,
parameters: {
frequency: 440,
},
data: {
type: "sine",
},
});
var square = context.createAudioWorkerNode(audioWorker, {
numberOfInputChannels: 0,
numberOfOutputChannels: 1,
parameters: {
frequency: 440,
},
data: {
type: "square",
},
});
sine.connect(context.destination);
square.connect(context.destination);
function Sine (node) {
node.onaudioprocess = this.processBlock.bind(this);
this.clock = 0;
}
Sine.prototype = {
processBlock (event) {
let blockSize = event.parameters.frequency.length;
for ( let output of event.outputBuffers ) {
for ( let i = 0; i < blockSize; i++ ) {
let phase = (this.clock + i) * event.parameters.frequency[i] / event.sampleRate;
output[i] = Math.sin(Math.PI * phase);
}
}
this.clock += blockSize;
}
};
self.addEventListener("onaudionodecreated", function (event) {
if ( data.type === "sine" ) {
new Sine(event.node);
}
});
function Square (node) {
node.onaudioprocess = this.processBlock.bind(this);
this.clock = 0;
}
Square.prototype = {
processBlock (event) {
let blockSize = event.parameters.frequency.length;
for ( let output of event.outputBuffers ) {
for ( let i = 0; i < blockSize; i++ ) {
let phase = (this.clock + i) * event.parameters.frequency[i] / event.sampleRate;
output[i] = Math.round(phase % 1) * 2 - 1;
}
}
this.clock += blockSize;
}
};
self.addEventListener("onaudionodecreated", function (event) {
if ( data.type === "square" ) {
new Square(event.node);
}
});
importScripts("square.js", "sine.js");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment