/******************************************************************************/
// Given a MIDI file as an argument, PlayMIDIFile plays a .mid file from the
// command line.
//
// Roy Vanegas: rvanegas@hunter.cuny.edu
/******************************************************************************/

import java.io.*;          // For File
import javax.sound.midi.*; // For MIDI

public class PlayMIDIFile
{

   static Sequence sequence;   // MIDI sequence
   static Sequencer sequencer; // Player for MIDI sequences

   /**
    * Print the proper usage of this program when the user either enters no
    * MIDI file name, or too many filenames.
    */
   public static String usage()
   {
      return "\tUsage\n\tjava PlayMIDIFile <midifile.mid>";
   }

   public static void main( String[] args )
   {
      if( args.length == 0 )
      {
         System.out.println( "No MIDI file name specified.\n" + usage() );
         System.exit( 1 );
      }
      else
         if( args.length > 1 )
         {
            System.out.println( "Too many arguments.\n" + usage() );
            System.exit( 1 );
         }

      try
      {
         /**
          * Line 1: Get the MIDI filename
          * Line 2: Assign the MIDI file's tracks to sequence; throws
          *         IOException
          * Line 3: Now get a sequencer, which is needed to play a MIDI file
          *         (analogous to "getting a CD player")
          * Line 4: Open the sequencer, (open the CD player's tray); throws
          *         MidiUnavailableException
          * Line 5: Assign the MIDI sequence to the sequencer (place CD in
          *         player);throws InvalidMidiDataException
          * Line 6: Start the sequencer (press play on the CD player)
          */

/* 1 */  File midiFile = new File ( args[ 0 ] );
/* 2 */  sequence = MidiSystem.getSequence( midiFile );
/* 3 */  sequencer = MidiSystem.getSequencer();
/* 4 */  sequencer.open();
/* 5 */  sequencer.setSequence( sequence );
/* 6 */  sequencer.start();

         while( sequencer.isRunning() )
            ;

         sequencer.close();
         System.exit( 0 );
      }
      catch( InvalidMidiDataException badMIDI ) { badMIDI.printStackTrace(); }
      catch( IOException ioe )                  { ioe.printStackTrace(); }
      catch( MidiUnavailableException mue )     { mue.printStackTrace(); }
  }
}
