Usage:
1) Include into your package
2) In your game make a MidiPlayer object
private MidiPlayer midiPlayer;
3) Pass a file and play.
midiPlayer = new MidiPlayer( "test.mid" );
midiPlayer.play();
4) Rock out
Code: Select all
/**@class MidiPlayer.java
* @date Nov 23, 2008
* @author Jesse Schipilow
* @contact schi0102@algonquincollege.com, jesse_schipilow@hotmail.com
*/
package model;
import javax.sound.midi.*;
import java.io.*;
/** Midi Player is capable of loading, stopping and playing .mid files
* @param midiFile File path to mid, (ie. "c:/example.mid")
*/
public class MidiPlayer {
private Sequencer sequencer = null; // The "midi player"
private Sequence sequence = null; // The "midi file"
/** Constructs a Midi Player and loads a midi file
* @param midiFile String containing file path to mid */
public MidiPlayer( String midiFile ) {
load(midiFile);
}
/** Start sequencer (Play loaded .mid file through speakers) */
public void play() {
if (sequencer != null)
sequencer.start();
}
/** Stop the sequencer (Stop .mid from playing) */
public void stop() {
sequencer.stop();
}
/** Load .mid file and prepare sequencer for playing
* @param midiFile String containing file path to mid */
public void load ( String midiFile ) {
if (sequencer != null) {
sequencer.stop();
sequencer.close();
}
try {
sequence = MidiSystem.getSequence(new File(midiFile));
//sequence = MidiSystem.getSequence(new URL("http://www.example.com/music.mid"));
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
} 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! Check .mid filepath");
}
}
}