Search code examples
angularaudioxmlhttprequestarraybuffer

Angular load file with xmlHttpRequest


I'm trying to play an mp3 file in my angular web app. So I'm trying to load it in my component with an XMLHttpRequest to get it as an ArrayBuffer like this :

public loadFile = () => {
  if (this.context === undefined) {
    return;
  }
  this.xhr = new XMLHttpRequest();
  this.xhr.open("GET", "./plucky.mp3", true);
  this.xhr.responseType = "arraybuffer";
  this.xhr.onload = this.onLoadComplete;
  this.xhr.send();
}

but I'm getting an ERROR 404 NOT FOUND although the mp3 is located in the same folder of my component. How can I load it as an ArrayBuffer?

Thank you.


Solution

  • Move the file to the assets folder in src and give that path:

    this.xhr.open("GET", "assets/plucky.mp3", true);
    

    PS: It might not work in the StackBlitz for the reason that StackBlitz is intermittently not recognizing the mp3 file. But it would work without any issues. Any such asset needs to be added to the assets folder in the src folder and then Angular CLI bundles it as a part of the Application Package as configured in the angular.json and thus it's accessible via relative urls.


    Here's a Sample StackBlitz for your ref.


    Here's also a Working Demo for your ref. In it, you should be able to see the logs on the console and the call to get the music file in the network tab of Dev Tools.