Yuvraj Singh
Yuvraj Singh

Reputation: 115

How to migrate to AudioWorkletNode from ScriptProcessorNode

At the moment I have the following code

AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext({latencyHint: 'interactive'});
processor = context.createScriptProcessor(bufferSize, 1, 1);
processor.connect(context.destination);
context.resume();

I need to migrate the AudioWorkletNode. The main function here is the "createScriptProcessor". I am struggling to find the equivalent of this. Please help!

Upvotes: 4

Views: 4076

Answers (2)

Ahmad Zuhair
Ahmad Zuhair

Reputation: 49

It becomes two lines:

await context.audioWorklet.addModule( url_worklet );
processor = new AudioWorkletNode( context , 'worklet-processor', {} );

And the content of the "processor.onaudioprocess" function goes to an external object, but you can still write it in the same script as follows:

let url_worklet = URL.createObjectURL( new Blob([ '(', function(){

  class WorkletProcessor extends AudioWorkletProcessor { 
    constructor (options) { super(); }
    process(inputs, outputs) {

      console.log( inputs[0][0] ); // the onaudioprocess code here

      return true; 
    }
  }
  registerProcessor('worklet-processor', WorkletProcessor);

}.toString(), ')()' ], { type: 'application/javascript' } ) );
    

The names "WorkletProcessor" and "'worklet-processor'" can be edited.

Enjoy

Upvotes: 3

Raymond Toy
Raymond Toy

Reputation: 6048

Instead of createScriptProcessor, you need to something more complicated. You can find a couple of examples in the spec itself. There are other demos with the basic Hello Audio Worklet being a good place to start.

Upvotes: 2

Related Questions