Playing multiple files in MediaPlayer one after other In android

前端 未结 3 2025
情歌与酒
情歌与酒 2020-12-16 09:01

I am having Problem in playing multiple mp3 files in MediaPlayer for android ...It plays all files together and creates mess.I want the solution that it just play each file

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 09:32

    You can try something like this:

    public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener
    {
        int[] tracks = new int[3];
        int currentTrack = 0;
        private MediaPlayer mediaPlayer = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          tracks[0] = R.raw.say1;
          tracks[1] = R.raw.say2;
          tracks[2] = R.raw.say3;
          mediaPlayer = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
          mediaPlayer.setOnCompletionListener(this);
          mediaPlayer.start();
        }
    
        public void onCompletion(MediaPlayer arg0) {
          arg0.release();
          if (currentTrack < tracks.length) {
            currentTrack++;
            arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
            arg0.setOnCompletionListener(this);
            arg0.start();
          }
        }
    }
    

提交回复
热议问题