Page 1 of 1

JAVA - Midi player

Posted: Fri Mar 06, 2009 11:35 pm
by Spikey
This is a simple Java midi player that you can plop into your projects for instant midi awesomeness.

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");
		} 

	}

	
}

Re: JAVA - Midi player

Posted: Sat Mar 07, 2009 1:27 am
by MarauderIIC
5) ???
6) Profit

I know you don't post much, so thanks for contributing.

Re: JAVA - Midi player

Posted: Sat Mar 07, 2009 4:30 pm
by Arce
Hey, I appreciate this post. Didn't know you were a Java devver. ;p

I'll give it a test sometime. Sick atm. =/