0

I am working on a small sound player which plays songs. I am using the TinySound library https://github.com/finnkuusisto/TinySound. And as I can see from the API, it does come with a method called .done() which tells me wheter a Music object is finished playing or not, but how can I test for it while playing?

I have currently created a JFrame with buttons and a Jlist which displays the songs, but I understand that if I try some sort of while loop to listen for wheter or not the song is finished I wont be able to use the other buttons such as stop, pause etc.

I was thinking somewhere along this line (pseudo code):

while(theSong.playing()){
    if(theSong.done()){
      playNext();
    }
 }

The problem is that when entering the while loop, I am not able to use any other functions in my program. If anyone wants to see some sample code, please let me know!

Sindre M

  • 1
    Sounds like you may need to start a separate Thread or something... – xdhmoore Jan 20 '15 at 18:03
  • I have never used threads, but if anyone would explain or link to some tutorial I would appreciate that a lot! – Sindre Moldeklev Jan 20 '15 at 18:08
  • 1
    Simple thread example: http://stackoverflow.com/questions/2531938/java-thread-example – Leandro Carracedo Jan 20 '15 at 18:09
  • i would also suggest using a timer to only do the body of the loop every so many milliseconds or something so you aren't just cranking cpu cycles. No clue how to do that in Java. – xdhmoore Jan 20 '15 at 18:14
  • While you are going to use a thread you also need some kind of notification. Thats where you will use a Observer pattern.[See here](http://en.wikipedia.org/wiki/Observer_pattern) – Murat Karagöz Jan 20 '15 at 18:14

1 Answers1

0

Running this while on the same thread as your GUI will make the interface stuck. You can achieve the desired functionality using SwingUtilities invokeAndWait method:

SwingUtilities.invokeAndWait(new Runnable() {
   public void run() {
       while(theSong.playing()) {
           if(theSong.done()) {
               playNext();
           }
       }
   }
}
  • Would I only provide the SwingUtilities for this particular event or do I need to provide the run() method for the whole application? Just thinking that because everything else runs as desired? – Sindre Moldeklev Jan 20 '15 at 18:31
  • @SindreMoldeklev, you can use it whenever you're going to perform something that would otherwise stuck the thread the Swing is running. This is often used with Progress Bar, to execute something on the background while updating the bar completion. – Bruno Marco Visioli Jan 20 '15 at 18:49