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.
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With