WebAudio / web-audio-api

The Web Audio API v1.0, developed by the W3C Audio WG
https://webaudio.github.io/web-audio-api/
Other
1.05k stars 167 forks source link

Setting parameters for an AudioWorkletNode #1942

Closed joshreiss closed 5 years ago

joshreiss commented 5 years ago

Hi all, I'm trying to set the parameters of an audio worklet when defining it as is done in the bitcrusher example at https://www.w3.org/TR/webaudio/#the-bitcrusher-node In that example, a worklet was created with parameters set the same way they can be for any audio node, that is, like new GainNode(this.context, { gain:0.5}); But when I do this, it doesn't set the parameter to the new value and it gives no error message.

Can anyone explain why the following isn't working? I've made the example as simple as possible. Thanks in advance.

---------The main js file ---------

let context= new AudioContext(); context.audioWorklet.addModule('example.js').then(() => { let test = new AudioWorkletNode(context, 'noise-generator',{G: 0.1}); test.connect(context.destination); console.log(test.parameters.get('G').value); //Gives G as 0.2, when it should give 0.1 });

--------------- example.js ---------

registerProcessor('noise-generator', class extends AudioWorkletProcessor { static get parameterDescriptors () { return [{name:'G',defaultValue:0.2}] } constructor() { super(); } process(inputs, outputs, parameters) { for (let i=0;i<outputs[0][0].length;++i) outputs[0][0][i]= parameters.G[0] (2Math.random()-1); return true; } });

hoch commented 5 years ago

The current example is outdated. Usually this issue tracker is not for this kind of question, so please use other Q&A forum for it. With that said, it's WG's fault to have an outdated code example. See below:

// index.html
const start = async () => {
  const context = new AudioContext();
  await context.audioWorklet.addModule('./processor.js');
  const node = new AudioWorkletNode(context, 'kaboom', {parameterData: {G: 0.1}});

  console.log(node.parameters.get('G').value); // 0.10000000149011612 in Chrome 77
};

start();
// processor.js
class MyProcessor extends AudioWorkletProcessor {
  static get parameterDescriptors() {
    return [{name: 'G', defaultValue: 0.2}];
  }

  constructor(options) {
    super(options);
  }

  process() {
    return true;
  }
}

registerProcessor('kaboom', MyProcessor);

The trick is to pass the option object to AWP's super constructor.

joshreiss commented 5 years ago

Thanks! Using {parameterData: {G: 0.1}} instead of {G: 0.1} in the AudioWorkletNode definition fixes the problem. I guess this should be fixed in the example at https://www.w3.org/TR/webaudio/#the-bitcrusher-node

And sorry for the rookie mistake. Any future queries like this will go to the other forum.