package music;
import javax.sound.midi.*;


/*
 * Class to simplify the interface to the Java Sound API
 * 
 */

public class MidiPlayer {


    /* 
     * local data
     */
    
    private Receiver receiver;
    private Synthesizer synth;
    private int beat;

    
    /* 
     * Java constructor 
     * Initializes all fields
     */

    private MidiPlayer (Synthesizer s, Receiver r, int b) {
        synth = s;
        receiver = r;
        beat = b;
    }
    

    /* 
     * Create a new instance of the MidiPlayer object,
     * Takes a beat as an argument, that is used to determine
     * how long a quarter note will play (in milliseconds) using
     * that player
     */

    public static MidiPlayer create (int b) {
        try {
            Synthesizer synth = MidiSystem.getSynthesizer( );
            synth.open( );
            Receiver synthRcvr = synth.getReceiver();
            return new MidiPlayer (synth,synthRcvr,b);
        } catch (MidiUnavailableException e) {
            throw new RuntimeException ("MIDI does not seem available.");
        }
    }


    /* 
     * Close the object
     * Required to free the MIDI resources 
     */
    
    public void close () {
        this.synth.close ();
    }


    /* 
     * Play a note using the player
     * Actual length of the note is determine by the beat
     * supplied when the player was created
     */

    public void play (Note n) {
        try {
            ShortMessage start = new ShortMessage();
            ShortMessage end = new ShortMessage();
            start.setMessage (ShortMessage.NOTE_ON,0,n.number(),n.volume());
            end.setMessage (ShortMessage.NOTE_OFF,0,n.number());
            receiver.send(start,-1);
            Thread.sleep((int) n.length(this.beat));
            receiver.send(end,-1);
        } catch (Exception e) {
            return;
        }
    }
    
}