1

I'm trying to create an AudioWorklet in React. I'm using create-react-app and importing scripts that are working outside the context of React into App.jsx. It is failing to instantiate my AudioWorkletNode extension and throwing the following error:

   Failed to compile.
./src/worklet/worklet-node.js
  Line 2:  'AudioWorkletNode' is not defined  no-undef

The code:

 // The code in the main global scope.
    class MyWorkletNode extends AudioWorkletNode {
        constructor(context) {
          super(context, 'my-worklet-processor');
        }
      }

      let context = new AudioContext();

      context.audioWorklet.addModule('processor.js').then(() => {
        let node = new MyWorkletNode(context);
      });

The same exact code is successfully initializing the AudioWorklet, so I'm a little baffled as to why AudioWorkletNode is not being recognized.

spidercatnat
  • 439
  • 1
  • 5
  • 15

1 Answers1

5

Create React App is configured to enforce that you access browser APIs like this with a window. qualifier. This way it's clear you're using a global, and didn't forget to import something (which is very common).

This should work:

class MyWorkletNode extends window.AudioWorkletNode {
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
  • (In the future releases, ESLint will be aware of this global by default, and you will be able to remove `window.`) – Dan Abramov Apr 23 '18 at 00:03
  • Although the next bug has made itself known-- DOMException: User aborted request even though I've attached everything to a click handler. Hmm? – spidercatnat Apr 23 '18 at 01:10
  • Doesn't seem related to your question. – Dan Abramov Apr 23 '18 at 23:08
  • @bloom.510 For the _"DOMException: User aborted request"_ error see [this answer](https://stackoverflow.com/questions/49972336/audioworklet-error-domexception-the-user-aborted-a-request/51469624#51469624), but as mentioned, it's a separate question. – John Weisz Aug 01 '18 at 18:23
  • 2
    Hi from 2020, after changing to `window.AudioWorkletNode` getting: `TypeError: Class extends value undefined is not a constructor or null` – Dima Gimburg Jun 13 '20 at 17:35
  • I got "TypeError: Class extends value undefined is not a constructor or null" but I think thats because you are defining your class inline rather than from its own file via addModule(). Its now gone for me once not trying to define it without using another file. I suspect addModule internally knows how to handle AudioWorkletNode but the DOM doesn't? – Dessus Mar 02 '21 at 00:50