set number of output channels in AudioWorkletProcessor

Viewed 592

If I create an audio context, the destination node has 2 channels (for stereo output) and the AudioWorkletNode appears to have 2 channels:

var audioContext = new AudioContext()
console.log(audioContext.destination.channelCount); // 2 channels

audioContext.audioWorklet.addModule('testworker.js').then(()=>{
   var node = new AudioWorkletNode(audioContext, 'test');
   console.log("channel count", node.channelCount); // also 2 channels?
   node.connect(audioContext.destination);
});

However, within the process function, the output only has 1:

testworker.js:

class Test extends AudioWorkletProcessor {
   process(inputs, outputs, parameters) {
      console.log("output channels: ", outputs[0]); // Array [ Float32Array(128) ] (1 channel)
      return false;
   }
}

registerProcessor("test", Test);

Is there a way to specify the number of output channels for an audio worklet processor?

with the now-deprecated script processor system, you specify the number of inputs/outputs in the constructor: audioContext.createScriptProcessor(bufferSize, inputCount, outputCount) but I don't see how to do that with audio worklets

3 Answers

Since you don't give an example of what you're trying to do it's hard to give good advice. But you should begin with looking at AudioWorkletNodeOptions, and the description on configuring channels is a good place to start.

I have done something similar and worked out how to do it.

The comments on the code explain the stuff you need to add.

The code runs on atom live server therefore it might not work when running it on here, however it does produces a stereo sound using 2 channels.

registerProcessor('noise-generator',class extends AudioWorkletProcessor {
  process(inputs, outputs) {
    for (let i=0;i<outputs[0][0].length;++i){
      outputs[0][0][i]=2*Math.random()-1  //ouputs sound to left side
      outputs[0][1][i]=2*Math.random()-1 //outputs sound to right side, added extra output and set 2nd channel to 1
  }
    return true
  }
})
<button onclick="context.resume()">Start</button>
<script>
  let context= new AudioContext()
  context.audioWorklet.addModule('basicnoise.js').then(() => {
    let myNoise = new AudioWorkletNode(context,'noise-generator', {outputChannelCount : [2]}) //added 2 output channels
    myNoise.connect(context.destination)
  })
  console.log(context.sampleRate); 
</script>

To get stereo output I had to use:

    workerNode = new AudioWorkletNode(ctx, "audio-proc", {
        numberOfOutputs : 2, 
        outputChannelCount : [2, 2]
    });
Related