I was working on an application that used the WEB AUDIO API. And things were going well, untill I got this error:
DOMException: Failed to construct 'AudioWorkletNode': AudioWorkletNode cannot be created: AudioWorklet does not have a valid AudioWorkletGlobalScope. Load a script via audioWorklet.addModule() first.
I have searched the internet for this, and I couldn't figure it out.
I will show you all relevant code.
record(){
const toast = useToast();
if(!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
if(navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({audio:true}).then((stream) => {
this.success(stream);
}).catch((e) => {
console.error(e);
})
} else {
toast.error('getUserMedia is not supported in this browser');
}
},
success(e){
let audioContext = window.AudioContext;
let context = new audioContext();
context.audioWorklet.addModule('../../../public/js/processor.js');
console.log(context);
let audioWorkletNode = new AudioWorkletNode(context, 'worklet-processor');
}
and my processor (it is empty I know)
class WorkletProcessor extends AudioWorkletProcessor {
constructor(){
super();
}
process(){
return true;
}
}
registerProcessor('worklet-processor', WorkletProcessor);
I hope my question is clear. Thanks in advance.
I think the problem is that the promise returned by addModule()
is not waited for. Turning your success()
function into an async
function and using await
to wait for the promise to resolve should solve the problem.
success async (e) {
let context = new AudioContext();
await context.audioWorklet.addModule('../../../public/js/processor.js');
let audioWorkletNode = new AudioWorkletNode(context, 'worklet-processor');
}