Midi Player in JavaThis snippet shows how to play music Midi files (musical sequences). In order to play midi sequences, the Midi Sequencer is needed which is retrieved by MidiSystem.getSequencer() method. Then midi sequences from the midi file are read by FileInputStream and then feed to the sequencer to play. The midi sound can be stopped by calling the sequencer.close() method.
package com.livrona.snippets.audio;

import java.io.FileInputStream;

import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;

/**
 * Midi Player using the Midi Sequencer.
 * 
 * @author mvohra
 * 
 */
public class MidiPlayer {

	private Sequencer sequencer = null;

	/**
	 * Stop Playing the sequence
	 */
	private void stopPlaying() {
		// stop the current sequence
		sequencer.stop();

		// close it
		sequencer.close();

	}

	/**
	 * Starts Playing the Midi File
	 */
	private void startPlaying(String midiFile) {
		try {
			// get the midi sequencer from the system
			sequencer = MidiSystem.getSequencer();

			// if the system does not support midi
			if (sequencer == null)
				throw new MidiUnavailableException();

			// open
			sequencer.open();
			// get handle to midi file
			FileInputStream is = new FileInputStream(midiFile);

			// get sequence from the file stream
			Sequence Seq = MidiSystem.getSequence(is);

			// pass the sequence to the sequencer
			sequencer.setSequence(Seq);

			// start the sequencer
			sequencer.start();
		} catch (Exception e) {
			System.out.println("Failed to start the midi sound.. : "
					+ e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * App Launcher , main(..) method
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		if (args.length != 1) {
			System.out
					.println("Usage: java com.livrona.snippets.audio.MidiPlayer <midi file>");
			System.exit(0);
		}

		String midiFile = args[0];
		System.out.println("File : " + midiFile);

		// create the player
		MidiPlayer player = new MidiPlayer();

		// start
		player.startPlaying(midiFile);
		System.out.println("Midi file is playing..");

		Thread.sleep(10000);
		System.out.println("About to stop the midi sequence..");

		// stop
		player.stopPlaying();
	}
}