简体   繁体   中英

How to loop OnCompletionListener

I'm trying to create a mock radio app with about 100 songs that'll be played randomly, and occasionally interrupt the music with other audio files.

This is the snippet that's giving me trouble:

mp.start();
while(true)
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mPlayer) {
        radio.playRadio();
    }
});

I've gotten the code to work with some infinite loops that would hang the app (I couldn't even change volume), which is why I thought the OnCompletionListener would break that up. Instead, it doesn't even seem to go into the radio.PlayRadio function.

What I'm expecting to happen is that the program starts with the starting audio, then while that's playing goes into the while loop and stops at the OnCompletionListener. When it completes, goes into the function, performs the actions in there (sets media, plays them), exits, then loops back to the wait for complete.

If I take out the while(true) , it goes into the function, so somehow the while loop is stopping everything, and reading documentation and other questions isn't explaining why.

You can use recursive method to tackle the problem. For example, if you are playing the song, you can create the following method:

private void playSong(Uri uri) {
  // this is just example, don't expect the code to works.
  MediaPlayer mp = new MediaPlayer();
  mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
  mp.setDataSource(getApplicationContext(), uri);
  mp.prepare();
  mp.start();
  mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mPlayer) {
      // get the next uri here
      // assume there is next uri.
      playSong(nextUri);
    }
  });

}

You should not use while loop to block your code. Instead, you need to rely on the message sent by the listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM