Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to implement empty while loop to hold control

I am playing audio in background and I want the control of program to stay stand still till the audio playing is over for that I am using empty while loop as follows

while(isPlaying==true){};
mediaPlayer.stop();

as you can see while loop holds program control till audio is playing and after that next instruction is executed. This is working fine but I came to know that this is not a proper way to do this empty-while is expensive I am searching for alternative. Please Help.

like image 334
DCoder Avatar asked Mar 21 '23 06:03

DCoder


2 Answers

Assuming your program is in Java (...why did you give it three language tags?) You have a few options. You could use a proper synchronization event, e.g.:

// fields
Object playerStopEvent = new Object();
boolean isPlaying;

// in your media player, when playback is complete:
synchronized (playerStopEvent) {
   isPlaying = false;
   playerStopEvent.notifyAll();
} 

// elsewhere, when waiting for playback to complete:
synchronized (playerStopEvent) {
   while (isPlaying) {
       try {
           playerStopEvent.wait();
       } catch (InterruptedException x) {
           // abort or ignore, up to you
       }
    }
}
mediaPlayer.stop();

See the official tutorial on Guarded Blocks for more examples.

You could also just have mediaPlayer call some callback when it is finished, and e.g. disable GUI components when you start playing and re-enable them when the finished callback is called (you could also use an event listener approach here).

Without more info, I recommend the latter, as it won't prevent you from doing other unrelated things (or keep your program from responding at all) while the player is playing, but the former may be more appropriate depending on your situation.

If it's in C or C++ the concept is the same. Use whatever equivalent of condition variables / events you have for the first option, or whatever equivalent of callbacks / listeners / signals+slots you have for the second.

like image 124
Jason C Avatar answered Mar 31 '23 21:03

Jason C


well, in my humble opinion, it's better to use another implementation.. try to use thread so that it won't hang your program in there (it's a background audio afterall; you might want to do something else while the audio is playing)..

try to check this page out..

like image 39
Yohanes Khosiawan 许先汉 Avatar answered Mar 31 '23 19:03

Yohanes Khosiawan 许先汉