Search code examples
javascriptweb-worker

ReferenceError when trying to new up 'Audio' object within web worker


function buildBlobUrl(func) {
  let blobUrl = URL.createObjectURL(new Blob(['(',
    func.toString(),
    ')()'
  ], {
    type: 'application/javascript'
  }));
  return blobUrl;
}

function webWorkerFunction() {
  let audio = new Audio();
}

let blobUrl = buildBlobUrl(webWorkerFunction);
let webWorker = new Worker(blobUrl);

If I run the above code, I get an error saying Uncaught ReferenceError: Audio is not defined. Is there anyway I can utilize the Audio object within my web worker function?


Solution

  • No,

    The Audio constructor does return an HTMLAudioElement DOM Element, and Web Workers don't have access to the DOM, we thus can't create DOM Elements from there.
    And since we still can't really have a BaseAudioContext in a Worker either, there is no true alternative to playing this media 100% from the Worker.