Search code examples
javaandroidandroid-mediaplayer

MediaPlayer seekTo random duration


I have a MediaPlayer and i stream an MP3 file from a link i want the music to be randomize based on the MP3's duration.

I have tried using the Random class and getDuration() from MediaPlayer and seekTo() but failed maybe because of buffering issue.

This below code just reset() the file because i have failed getting it to a random duration. Please help me out

try {
      mediaPlayer.setDataSource(MainActivity.this, uri);
      mediaPlayer.prepare();
      mediaPlayer.start();
     } catch (IOException e) {
      dialog.dismiss();
}

Solution

  • Try this for random position:

    randomPosition = ThreadLocalRandom.current().nextInt(0, mediaPlayer.getDuartion() + 1);
    

    Then seek:

    mediaPlayer.seekTo(randomPosition);