Search code examples
javaandroidandroid-mediaplayermedia-player

MediaPlayer seekTo method is not accurate


I want to seek to a specified position on mp3 file, my proplem is the MediaPlayer seek to about 31 seconds ahead, for example I want to seek to 136540 mSeconds which means 2 Minutes and 16 Seconds, the MediaPlayer seek instead to 1 Minutes and 45 Seconds

here is my code

 File[] ffile1 = ContextCompat.getExternalFilesDirs(this, null);
    String mp3FilePath =ffile1[0].getAbsolutePath() + File.separator + "002.mp3";
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(mp3FilePath);
        SystemClock.sleep(1000);
        mediaPlayer.prepare();
        SystemClock.sleep(200);
        mediaPlayer.seekTo(136540);
        SystemClock.sleep(200);
        mediaPlayer.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Here is the mp3 file that I use https://download.quranicaudio.com/qdc/abdul_baset/mujawwad/2.mp3
Please help, Thanks


Solution

  • When it comes to MP3s, depending on their encoding, MediaPlayer can't always parse them correctly, and so the seek function is essentially broken. It has to do with the variable bit rate not being properly encoded in the MP3 itself.

    Instead of MediaPlayer, try using ExoPlayer. It's a fairly simple drop-in replacement, which shouldn't require you to change too much code