How to parse a MIDI file?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By I-Want-Answers

In Godot, I’d like to parse a MIDI file into a class or a dictionary, so that I can read its BPM, which notes it has, when the notes would play, etc. Like this website does: Tonejs Midi

There have been similar questions in this forum, but the ones I found were more complicated like a MIDI player or DAW functionality that ended up in “use a plugin” as the answer. I only want to retrieve the MIDI’s info, like the link above would do.

I’m mainly interested in answers for Godot 3.5, but Godot 4 answers are also welcome.

Thanks!

:bust_in_silhouette: Reply From: jgodfrey

This should definitely be doable in pure gdscript, but it’ll take some work. Essentially, you’ll need to create a binary file reader that’s capable of parsing the MIDI format. I’ve done similar work with (for example) image meta data (EXIF, IPTC, …). And, while it’s not really hard, it is somewhat tedious.

Some tips:

  • Find a MIDI file format spec. Maybe this.
  • Open and load a given MIDI file as a binary blob using Godot’s File methods
  • Process the binary blob using a StreamPeerBuffer, which provides all of the necessary mechanism to read the binary data in a way that matches the spec doc.
  • Store the loaded data in any format you see fit (for example, a Dictionary).