Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaPlayer play audio in background and play next one

I use below code to play audio in background:

String[] Path = new String[] {path1, path2, ...};
mMediaPlayer.setDataSource(Path[i]);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.seekTo(0);

While I play the first one Path[0] in background. I want to make it auto play next one Path[1] after Path[0] play finish, how to arrive it?

like image 503
brian Avatar asked Nov 27 '22 14:11

brian


2 Answers

You should override onCompletionListener like this,

mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {           
    public void onCompletion(MediaPlayer mp) {          
        Log.i("Completion Listener","Song Complete");
        mp.stop();
        mp.reset();
        mp.setDataSource([nextElement]);
        mp.prepare();
        mp.start();
    }
});

If you use a onPreparedListener in your MediaPlayer then you cal also use the prepareAsync command and ignore the .start().

like image 108
Andro Selva Avatar answered Jan 22 '23 02:01

Andro Selva


You need to set an OnCompletionListener to your MediaPlayer, in the listener set the source to path2, prepare and play. http://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html

like image 22
Tony Avatar answered Jan 22 '23 02:01

Tony