Search code examples
javascriptmp3

How do I read metadata properties from MP3 file in JavaScript?


I know questions similar to this have been asked before, specifically this one, but all the answers usually involve one of two things, both of which I'd like to avoid:

  1. Importing a new library, or,

  2. Using FileReader, which as far as I can tell, only works for user-inputted files.

I'm making a little game that includes the option to switch between several music tracks in the options menu, and I'd like to be able to show the track title and artist. I could adjust my song object so that I input information like title, artist, etc. into the code, but it just seems simpler to include that as metadata on the file so that I only have to input the filename. Is there any way I can read metadata off of files that aren't inputted by a user without using an extra library? Here's the Song object that I'm using, although it's pretty simplistic:

var Song = function(filename)
{
    this.intro = new Audio(); // the introduction of the song that leads into a loop
    this.intro.src = filename + "-intro.mp3";
    var temp = this;
    this.intro.addEventListener("ended", function() {
        this.currentTime = 0;
        temp.loop.currentTime = 0;
        temp.loop.play();
    });

    this.loop = new Audio(); // the main file that will be looped. Also has the relevant metadata
    this.loop.src = filename + ".mp3";
    this.loop.addEventListener("ended", function() {
        this.currentTime = 0;
        this.play();
    });
};

var songs = [
    new Song("track1"),
    new Song("track2"),
    new Song("track3")
];

Solution

  • Use mutag for this

    In your html add:

    <script src="sanjit1.github.io/mutag/dist/mutag.min.js"></script>

    and in your js add:

    const mutag = window.mutag;

    and using the variable filename,

    mutag.fetch(filename).then((tags) => {
          console.log(tags);
    });