Hrant Nurijanyan
Hrant Nurijanyan

Reputation: 929

Web Audio API Processor result

I am doing some audio processing with JS, using Web Audio API So I've created a custom Audio Worklet Processor in which I am processing some audio.

Here is a small example.

class MyProcessor extends AudioWorkletProcessor {
  process (inputs, outputs, parameters) {
    const someProcessedNumber = cppApiProcessor.process(inputs,outputs,parameters);
    return true; // to keep the processor alive
  }
}

You see variable someProcessedNumber comes from a cppApi and I don't know how to let the outer JS world know about that, as the Processor returns boolean (whether keep the node alive or not), and I cannot touch the data in outputs. ( I don't wanna change the outcoming audio, just process and give a number) How can I do that? Is there a better way to do this?

Upvotes: 1

Views: 713

Answers (1)

chrisguttandin
chrisguttandin

Reputation: 9136

You can use the port of an AudioWorkletProcessor to send data back to the main thread (or any other thread).

this.port.postMessage(someProcessedNumber);

Every AudioWorkletNode has a port as well which can be used to receive the message.

Using the MessagePort will generate some garbage on the audio thread which makes the garbage collection run from time to time. It's also not the most performant way to transfer data.

If that's an issue you can use a SharedArrayBuffer instead which the AudioWorkletProcessor uses to write the data and the AudioWorkletNode uses to read the data.

ringbuf.js is a library which aims to make this process as easy as possible.

Upvotes: 3

Related Questions