How to play a midi file from a Java application

By Angsuman Chakraborty, Gaea News Network
Friday, November 12, 2004

I got a question on how to play a midi file from a Java application.

Presented below is a simple demonstration program.

You can view it better here.

import javax.sound.midi.*;
import java.io.*;

/** Plays a midi file provided on command line */
public class MidiPlayer {
    public static void main(String args[]) {
        // Argument check
        if(args.length == 0) {
            helpAndExit();
        }
        String file = args[0];
        if(!file.endsWith(".mid")) {
            helpAndExit();
        }
        File midiFile = new File(file);
        if(!midiFile.exists() || midiFile.isDirectory() || !midiFile.canRead()) {
            helpAndExit();
        }
        // Play once
        try {
            Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.setSequence(MidiSystem.getSequence(midiFile));
            sequencer.open();
            sequencer.start();
            while(true) {
                if(sequencer.isRunning()) {
                    try {
                        Thread.sleep(1000); // Check every second
                    } catch(InterruptedException ignore) {
                        break;
                    }
                } else {
                    break;
                }
            }
            // Close the MidiDevice & free resources
            sequencer.stop();
            sequencer.close();
        } catch(MidiUnavailableException mue) {
            System.out.println("Midi device unavailable!");
        } catch(InvalidMidiDataException imde) {
            System.out.println("Invalid Midi data!");
        } catch(IOException ioe) {
            System.out.println("I/O Error!");
        } 

    }  

    /** Provides help message and exits the program */
    private static void helpAndExit() {
        System.out.println("Usage: java MidiPlayer midifile.mid");
        System.exit(1);
    }
}
Filed under: Java Software
Discussion

Peter
May 12, 2007: 7:45 am

Man, this is perfect. Very useful.

November 30, 2004: 11:26 pm

Thanks!

This is interesting! I used JDK 1.5 and it compiled and ran fine on my system. Which version of jdk are you using?

Angsuman


Gyorgy Molnar
November 30, 2004: 4:14 pm

It didn’t work for me at the first. I had to replace the order of two lines. After it was perfect. Thanks for the demo.
Original:
sequencer.setSequence(MidiSystem.getSequence(midiFile));
sequencer.open();
sequencer.start();
Modified:
sequencer.open();
sequencer.setSequence(MidiSystem.getSequence(midiFile));
sequencer.start();


Karen (karry1412)
November 13, 2004: 3:29 am

Very helpful & informative!

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :