Parse midi files

Hey,

not sure if there is a library that does exactly what you need, but there is the javax.sound.midi package, that you can use to access the data from midi-files. Maybe using a sequencer would be better but here is an example that parses (one track of) a midi file and logs the note-on and note-off events.

import javax.sound.midi.*;

void setup() {
  String path = dataPath("some_midi_file.mid");
  File midiFile = new File(path);
  try {
    Sequence seq = MidiSystem.getSequence(midiFile);
    Track[] tracks = seq.getTracks();

    // how many tracks are there
    println("number of tracks: "+ tracks.length);

    // parse first track
    println("events of 1st track:");
    Track myTrack = tracks[0];
    for (int j =0; j< myTrack.size(); j++) {
      // get midi-message for every event
      if (myTrack.get(j).getMessage() instanceof ShortMessage) {
        ShortMessage m =  (ShortMessage) myTrack.get(j).getMessage();

        // log note-on or note-off events
        int cmd = m.getCommand();
        if (cmd == ShortMessage.NOTE_OFF || cmd == ShortMessage.NOTE_ON) {
          print( (cmd==ShortMessage.NOTE_ON ? "NOTE_ON" : "NOTE_OFF") + "; ");
          print("channel: " + m.getChannel() + "; ");
          print("note: " + m.getData1() + "; ");
          println("velocity: " + m.getData2());  
        }
      }
    }
    println();
  }

  catch(Exception e) {
    e.printStackTrace();
    exit();
  }
}

Maybe that helps as a starting point.

2 Likes