How to show seekbar with media player

Save

What is a SeekBar? Well according to android.developers.com, A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. Placing focusable widgets to the left or right of a SeekBar is discouraged. You must have seen a bar with your media player (audio or video). It helps you to navigate to a certain time of the audio or video you are using.

We are going to check that how we can achieve this in Android.

If you are not aware of the media player class then you can follow the below provided links to learn how to play the audios in your android app.

Playing Audio file online and offline

Let us begin with adding seek bar with your media player object.

We are gonna assume that you have you already have a Mediaplayer object initialized with your media. Now we will have to set the max value for the seek bar with the duration of the media file

and we need a handler which will constantly update the seek bar according to the media player object with the help of a Runnable. We are using this because only the main thread can update the UI.

the above handler updates the seek after every 50ms. You can change this time according to your requirement.

Now we have to call this handler when the audio starts to play. The below code segment shows how to do this.

and on pause, you can remove the callback.

 

The above process connects the seek bar to the media player but it will not seek the media player yet. For this, you will have to set an OnSeekBarChangeListener which will use the MediaPlayer’s seekTo function and seek the media file to a particular time.

this will seek to the position where ever the seek bar pointer is. The check fromUser is must otherwise it will keep seeking the media player on every second and the media output will come with some disturbance or lag.

That’s all you need to do to get a smoothly working SeekBar.

Thank you very much. This is Vedesh Kumar signing off.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


30 comments

  • Noor Eldali
    Thank you so much 🙂 this is the only code that worked with me
    • Vedesh Kumar (Moderator)
      We are glad that the blog helped you.
    • Prashantgosai26
      Yes @Noor Eldali
      This code work perfectatly (Work also in kotlin)
  • Bri
    This was super helpful thank you so much!
    • Vedesh Kumar (Moderator)
      Happy to help Bri.
  • Arman
    This is really very helpful. Thank you 🙂
    • Vedesh Kumar (Moderator)
      Welcome, Arman.
  • Saurabh
    This is Not Working For me
    • Vedesh Kumar (Moderator)
      Hello Sourabh, Can you please explain the issue a bit? Or you can share your code (If there is no issue).
  • iniaski
    thanks a lot, works fine !!!!
    • Vedesh Kumar (Moderator)
      You’re Welcome Iniaski… 😀
  • Programmer
    i have a problem that the song finished before the progress bar
    is there a solution pleaze thanks 🙂
    • Vedesh Kumar (Moderator)
      This should not happen as we have used the audio duration as the max value using the line “yourSeekbar.setMax(mMediaPlayer.getDuration());”

      Will it be possible for you to post your code here? So that we can have a look.

  • Prashant Kumar
    Attempt to invoke virtual method ‘boolean android.os.Handler.postDelayed(java.lang.Runnable, long)’ on a null object reference

    i am getting such error

    • Vedesh Kumar (Moderator)
      Have you initialized your mSeekbarUpdateHandler? Because the exception clearly says that the mSeekbarUpdateHandler in not initialized. If yes then can show me the code snippet where you have used it?
  • reza motahari
    I wrote the codes, but the program crashes when I play the sound:

    java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.SeekBar.setProgress(int)’ on a null object reference
    at com.example.video69.Activityfiles$1.run(Activityfiles.java:43)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5525)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

    • Vedesh Kumar (Moderator)
      It looks like you have not initialized yourSeekbar variable. Please check that.
  • mayar
    not working for me , seek bar does not run
    • Vedesh Kumar (Moderator)
      Can you share some more information about the issue?
  • Gyan Jyoti Das
    Audio is not playing smoothly
    • Vedesh Kumar (Moderator)
      Can you elaborate on the issue more? Or show us your code.
      • Gyan Jyoti Das
        import androidx.appcompat.app.AppCompatActivity;

        import android.media.AudioManager;
        import android.media.MediaPlayer;
        import android.os.Bundle;
        import android.os.Handler;
        import android.util.Log;
        import android.view.View;
        import android.widget.SeekBar;

        import java.util.Timer;
        import java.util.TimerTask;

        public class MainActivity extends AppCompatActivity {

        MediaPlayer mediaPlayer;
        AudioManager audioManager;
        Handler mSeekbarUpdateHandler;
        Runnable mUpdateSeekbar;

        public void play(View view){
        mediaPlayer.start();
        mSeekbarUpdateHandler.postDelayed(mUpdateSeekbar, 0);
        }
        public void pause(View view){
        mediaPlayer.pause();
        mSeekbarUpdateHandler.removeCallbacks(mUpdateSeekbar);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mediaPlayer = MediaPlayer.create(this, R.raw.demosong);
        SeekBar volumeControl = (SeekBar) findViewById(R.id.volumeSeekBar);

        final SeekBar songControl = (SeekBar) findViewById(R.id.songSeekBar);
        songControl.setMax(mediaPlayer.getDuration());

        volumeControl.setMax(maxVolume);
        volumeControl.setProgress(currentVolume);

        volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i,0);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
        });

        songControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        mediaPlayer.seekTo(i);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
        });

        mSeekbarUpdateHandler = new Handler();
        mUpdateSeekbar = new Runnable() {
        @Override
        public void run() {
        songControl.setProgress(mediaPlayer .getCurrentPosition());
        mSeekbarUpdateHandler.postDelayed(this, 50);
        }
        };

        }
        }

        • Gyan Jyoti Das
          audio get stuck while playing
          • Vedesh Kumar (Moderator)
            You can use prepareAsync() instead of prepare(). It should work fine.
        • Vedesh Kumar (Moderator)
          You should use mediaplayer on different thread rather then UI thread. It will play smooth then.
  • Omar Adel
    Thank you sooooo much
  • Aziz Fasih
    Thanks, brother its help me to resolve the issue in my app.
    • anchit (Moderator)
      Thanks
  • Owais Ali
    my seek bar behave abnormaly on to many touches other wise itwork smoothly any solution
    • anchit (Moderator)
      could you please elaborate on the abnormal behaviour ?
  • css.php

    Great Product, Great Team, and Great Support Service. And if you want to add more features to the product, they can submit any idea that comes to your mind. They really care about their clients and we are really happy and honored to deal with Webkul.

    Osama
    Talk to Sales

    Global

    Live Chat
    Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home