Java – a better way to implement an empty while loop to maintain control
I'm playing the background audio. I want the control of the program to remain stationary until the audio playback is over, because I use an empty loop, as shown below
while(isPlaying==true){}; mediaPlayer.stop();
As you can see, the while loop keeps program control until the audio is played, and then executes the next instruction It works, but I find it's not the right way to short - although it's expensive, I'm looking for an alternative Please help.
Solution
Suppose your program is Java (... Why do you give it three language tags?) You have several choices You can use appropriate synchronization events, such as:
// 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();
For more examples, please refer to the official tutorial of guarded blocks
You can also let mediaplayer call some callbacks when it is finished, such as disabling GUI components at the beginning of playback and re enabling them when calling the completed callbacks (you can also use the event listener method here)
Without more information, I recommend the latter because it won't prevent you from doing other irrelevant things when the player is playing (or make your program completely unresponsive), but the former may be more appropriate, depending on your situation
If it is in C or C, the concept is the same Use the same condition variable / event as the first option, or any equivalent callback / listener / signal slot for the second option