views:

708

answers:

2
+2  Q: 

Reading MIDI Files

What is the best way to read a MIDI file (chronologically) with multiple tracks? (Java)

Note: I don't want to play the MIDI file, just read the messages.

Couple ideas:

Is it safe to assume there are no note events shorter than the 1/64th note? Or should I visit every track and only move to the next tick after all other ticks tracks

  • Assume there is no midi event shorter than a 1/64th note, and move the current position tick count by that fix delta.
  • Visit every track and progress to the next earliest tick
+1  A: 

In Java, you can read a midi file with :

try {
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.setSequence(MidiSystem.getSequence(yourMidiFile));
        sequencer.open();
        sequencer.start();
        while(true) {
            if(sequencer.isRunning()) {
                try {
                    Thread.sleep(1000); // Check every second
                } catch(InterruptedException ignore) {
                    break;
                }
            } else {
                break;
            }
        }

} catch(Exception e) {
        System.out.println(e.toString());
} finally {
    // Close resources
    sequencer.stop();
    sequencer.close();
}

This code should read your midi files (even if there are multiple tracks)

Benoit Courtine
I don't necessarily want to play the sequence, just get the event messages in the tracks
srand
@srand I'm assuming this is just an example, you can use the MidiSystem, Sequence and Track classes to read out the MidiEvents stored in the file.
Jasper Bekkers
@Jasper Yeah, that's what I'm doing currently, however its a serial/sequential read of the midi file (and not chronological).
srand
+1  A: 

JFugue can read a MIDI file and sort the messages in chronological order.

The results can be read as JFugue MusicStrings (for example, C-sharp, 5th octave, whole note = "C#5w"), or you can write your own ParserListener and attach it to the MidiParser so you can output your own text.

David