How / where does one define AudioWorkletProcessor

1.9k views Asked by At

I have just started playing with the Web Audio API. I have been pouring over the API docs and see several examples. My issue is probably trivial and I am probably missing something fundamental.

I have the worker javascript file below. It came from an example whoes URL I have misplaced. I am using PyCharm as my IDE, if that matters, and it flags "AudioWorkletProcessor" as undefined. I have looked at a lot of pages at this point and I do not see any import or require statements that might define this interface.

I have just tried running the code in Firefox and Chrome and both throw exceptions on the undefined AudioWorkletProcessor line.

Should this be a "builtin"? Is it part of a library/module that I just haven't seen referenced yet?

class AudioRecorder extends AudioWorkletProcessor {
    static get parameterDescriptors() {
        return [
            {
                name: 'isRecording',
                defaultValue: 0,
                minValue: 0,
                maxValue: 1,
            },
        ]
    }

    process(inputs, outputs, parameters) {
        const buffer = []
        const channel = 0

        for (let t = 0; t < inputs[0][channel].length; t += 1) {
            if (parameters.isRecording[0] === 1) { // <2>
                buffer.push(inputs[0][channel][t])
            }
        }

        if (buffer.length >= 1) {
            this.port.postMessage({buffer})
        }

        return true
    }
}

registerProcessor('audio-recorder', AudioRecorder)
1

There are 1 answers

3
chrisguttandin On BEST ANSWER

The AudioWorkletProcessor base class and the registerProcessor() function are both available as globals in the AudioWorkletGlobalScope.

It's not possible to evaluate that code in the console. You need to load your JavaScript file like that:

audioContext.audioWorklet.addModule('path/to/your/file.js');

I guess your IDE is just not aware of the fact that you are editing something that is meant to be evaluated in that scope.