for(int i = 5; i < 60; i+=4){
track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(176, 1, 127, 0, i));
track.add(makeEvent(128, 1, i, 100, i + 2));
}
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
The point is to insert and fire a ControllerEvent (which you can listen for) with each Note On. Every time a ControllerEvent is heard, "la" is printed to the screen. I have found that the code given is insufficient, because the program hangs forever after the music finishes playing. The errata for Head First Java suggests putting the main thread to sleep for a bit (so the sequencer can finish playing back), then closing the sequencer:
sequencer.start();
Thread.sleep(1000 * 5);
sequencer.close();
This seemed rather ugly to me, and after browsing through the Java 6 API, I thought I had found a slightly better solution:
sequencer.start();
while(sequencer.isRunning());
sequencer.close();
This is where the bizarre behavior comes in. If the while statement is empty, using while(sequencer.isRunning()); or while(sequencer.isRunning()){}, the program runs forever. BUT, if I put something in the curly braces, like while(sequencer.isRunning()){ System.out.print("");), it works perfectly.
If the while loop is empty, it doesn't work.
If the while has something in it, even a print() statement that prints nothing, it works perfectly.
This...doesn't make any sense to me. I've tried disassembling the bytecode using javap -c with both an empty while loop and a while loop containing print(), and I can't see a significant difference between them.
Am I missing something obvious?