Ok so I'm learning from the book Head First Java, second edition, and I'm having a little trouble with some code. The code I'm working with compiles just fine and gives the output that I want(sort of) but whenever I run the code is doesn't stop, as if it was in an endless loop even though I don't have a single loop in my code. Ok so here is my code:
import javax.sound.midi.*;
public class MusicPlayer2 {
public static void main(String[] args){
MusicPlayer2 MusicPlayer = new MusicPlayer2();
if(args.length < 2){
System.out.println("Instrument and Note arguments");
} else {
int instrument = Integer.parseInt(args[0]);
int note = Integer.parseInt(args[1]);
MusicPlayer.play(instrument, note);
}
}
public void play(int instrument, int note){
try{
Sequencer Player = MidiSystem.getSequencer();
Player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
MidiEvent event = null;
ShortMessage first = new ShortMessage();
first.setMessage(192, 1, instrument, 0);
MidiEvent ChangeInstrument = new MidiEvent(first, 1);
track.add(ChangeInstrument);
ShortMessage a = new ShortMessage();
a.setMessage(144, 1, note, 100);
MidiEvent noteOn = new MidiEvent(a, 1);
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, note, 100);
MidiEvent noteOff = new MidiEvent(a, 16);
track.add(noteOff);
Player.setSequence(seq);
Player.start();
} catch(Exception ex){ex.printStackTrace();}
}
}
This code is meant to be run from the command line like this:
java MusicPlayer2 8 90 //The two numbers can be anything from 0 to 127
I wrote another version of this so that it has default values and when I run the code I get the sound, then it just keeps running as if it was in a loop but nothing is going on. Thanks in advance.