Actually, you shouldn't be using Thread.sleep() at all. If you want to block the current thread until the track has finished playing, you should use locks and conditions and add a meta event listener to the sequencer.
Stephan van Hulst wrote:Actually, you shouldn't be using Thread.sleep() at all. If you want to block the current thread until the track has finished playing, you should use locks and conditions and add a meta event listener to the sequencer.
Stephan, can you tell me where I can go to find out how to "use locks and conditions" and adding "a meta event listener to the sequencer"? Are those things new to Java 8 or Java 9? I'm mostly familiar with Java 6 and 7, and I don't remember anything about locks, conditions, or meta event listeners.
The high-level concurrency library was added in Java 5. The classes I'm referring to specifically are java.util.concurrent.locks.ReentrantLock and java.util.concurrent.locks.Condition. You can create a class that is responsible for playing a sequence and blocking until it's done:
Now, let's say that you expanded your application and you want to start playing your melody in the background when something happens and you want to continue doing things in the mean time, but when the application has finished, you want it to wait until the melody has finished playing. You would then use an ExecutorService to play your melody. Add this method to the SequencePlayer:
As long as the threads in the executor service are not daemons, any melodies that started playing will continue playing when the executor service is shut down. That will give you very gracious termination of your application.
Note that I haven't tested this code or that in the previous post. There may be some mistakes I haven't thought of.