G
G
Gregory2015-11-08 20:13:14
Java
Gregory, 2015-11-08 20:13:14

What is the correct way to use MediaPlayer in a loop?

There is a list of sound files:

static int[] sounds = {R.raw.cat1, R.raw.cat2, R.raw.cat3};

There is a method to play the file:
private void meowPlay(int fileName) {
  mp = MediaPlayer.create(this, fileName);
  mp.setLooping(false);
  mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    public void onPrepared(MediaPlayer mp) {
      mp.start();
    }
  });
  mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
      mp.release();
    }
  });
}

When the button is clicked, the following code is executed:
for (int i = 1; i <= 3; i++) {
  int rand = new Random().nextInt(2);
  meowPlay(sounds[rand]);
}

As a result, 3 audio files are played simultaneously . Can you please tell me how to make sequential playback of these files?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2015-11-08
@Rawen

You subscribe the player to the end of playback event, and in this event you launch the next file.
An alternative, but much worse option - check if the player has finished playing, if finished playing - feed him a new file. Naturally, you need to check in a separate thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question