Search code examples
dartweb-audio-api

How do I add an AudioWorkletProcessor to work with it in audioWorkletNode in Dart?


In pure JS I can do it:

const audioContext = new AudioContext();
const source = audioContext.createMediaElementSource(new Audio());

await audioContext.audioWorklet.addModule('./my-processor.js');
const processorNode = new AudioWorkletNode(audioContext, 'my-processor');

source.connect(processorNode);
processorNode.connect(audioContext.destination);

In Dart I can not do it:

var audioContext = AudioContext();
var source = audioContext.createMediaElementSource(AudioElement());

audioContext.audioWorklet // The getter 'audioWorklet' isn't defined for the class 'AudioContext'.
var processorNode = AudioWorkletNode(audioContext, 'my-processor');

source.connectNode(processorNode);
processorNode.connectNode(audioContext.destination);

I cannot find the audioWorklet property in the AudioContext class. I tried unsuccessfully to find in the documentation where else an audioWorklet or addModule could be located.

How do I add an AudioWorkletProcessor to work with it in audioWorkletNode in Dart?


Solution

  • if there isn't a method or property in a JS interop object you can use the dart:js_util:

    import 'package:js/js_util.dart' as jsu;
    
    var worklet = jsu.getProperty(audioContext, 'audioWorklet'));
    
    jsu.callMethod(worklet, 'addModule', ['./my-processor.js']));