Search code examples
angularsyntax-errorweb-audio-api

Unexpected Identifier Error when Importing a local file into AudioWorkletProcessor File


I am currently using Angular to build a video conferencing application. In one of my services, I try to incorporate the web audio api. The problem is when I try to add a script to the audio worklet using the addModule(AudioWorkletProcessorFileName.js) function, it throws a SyntaxError: Unexpected Identifier. I have found that it only happens when I try to import another file into AudioWorkletProcessorFileName.js. When I remove the import statement, everything works fine. There is more complex code that I want to import, but I wanted to start off with a more simple version of test.js (the file I want to import). I am not sure why this is the case. Am I missing some configuration settings in Angular or something else?

In audio.service.ts:

import { Injectable } from '@angular/core';
import { AudioContext, AudioWorkletNode } from 'standardized-audio-context';

@Injectable()
export class AudioService {
     audioCtx = new AudioContext();

     constructor() {}

     async createNewSetting(track) {
         // We need an audio context for the sound
         const srcNode = this.audioCtx.createMediaStreamTrackSource(track);
         const destNode = this.audioCtx.createMediaStreamDestination();

         // This will be the processor node
         await this.audioCtx.audioWorklet.addModule(
          './assets/worklet/audio-worklet-processor.js'
         );

         const spatialNode = new AudioWorkletNode(
             this.audioCtx,
             'spatial-processor'
         );

         // Connect the nodes
         srcNode.connect(spatialNode);
         spatialNode.connect(destNode);

         // Return the updated audio stream
         return destNode.stream.getTracks()[0];
    }
}

In audio-worklet-processor.js:

import TEST_VAR from './test.js'; // Will throw exception when I include this

class SpatialProcessor extends AudioWorkletProcessor {

    constructor() {
        super();
        console.log("In Constructor");
    }

    process (inputs, outputs, parameters) {
        console.log("In Process");
        return true;
    }
}

registerProcessor("spatial-processor", SpatialProcessor);

In test.js:

const TEST_VAR = 1;

export default {
    TEST_VAR
};

Solution

  • As mentioned in the comments above this was a bug in standardized-audio-context which did not correctly resolve relative paths inside of an AudioWorklet. It should be fixed in version 25.1.7 and above.