Fixing a seekbar on my Android music player

how to move seekbar automatically in android
simple music player android studio
android mediaplayer service example
android music player source code tutorial
synchronizing seekbar with the audio song android
android mediaplayer set seekbar
play audio in recyclerview android
play audio from url in android example

I've created a simple music player in Android which has a seekbar which displays the current position in the song playing. The forward, rewind, play and pause functions work correctly. What I am trying to do is have the seekbar actually move the position within the song. (at present the seekbar does not change the position within the song. Heres my code

public class MusicPlayerA extends Activity {

private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //set the layout of the Activity
    setContentView(R.layout.musicplayerview);
    //initialize views
    initializeViews();
}

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.pause();
        if (isFinishing()) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

public void initializeViews(){
    songName = (TextView) findViewById(R.id.songName);
    mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
    finalTime = mediaPlayer.getDuration();
    duration = (TextView) findViewById(R.id.songDuration);
    seekbar = (SeekBar) findViewById(R.id.seekBar);
    songName.setText("Druids Ad");  
    seekbar.setMax((int) finalTime);
    seekbar.setClickable(true);
}

// play mp3 song
public void play(View view) {
    mediaPlayer.start();
    timeElapsed = mediaPlayer.getCurrentPosition();
    seekbar.setProgress((int) timeElapsed);
    durationHandler.postDelayed(updateSeekBarTime, 100);
}

//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
    public void run() {
        //get current position
        timeElapsed = mediaPlayer.getCurrentPosition();
        //set seekbar progress
        seekbar.setProgress((int) timeElapsed);
        //set time remaining
        double timeRemaining = finalTime - timeElapsed;
        duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

        //repeat yourself that again in 100 miliseconds
        durationHandler.postDelayed(this, 100);
    }
};

// pause mp3 song
public void pause(View view) {
    mediaPlayer.pause();
}

// go forward at forwardTime seconds
public void forward(View view) {
    //check if we can go forward at forwardTime seconds before song endes
    if ((timeElapsed + forwardTime) <= finalTime) {
        timeElapsed = timeElapsed + forwardTime;

        //seek to the exact second of the track
        mediaPlayer.seekTo((int) timeElapsed);
    }
}

// go backwards at backwardTime seconds
public void rewind(View view) {
    //check if we can go back at backwardTime seconds after song starts
    if ((timeElapsed - backwardTime) > 0) {
        timeElapsed = timeElapsed - backwardTime;

        //seek to the exact second of the track
        mediaPlayer.seekTo((int) timeElapsed);
    }
}

 // handler for back button used on music player screen
 public void BackButton2 (View view) {

    MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
    mMediaPlayer.start();

    Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vib.vibrate(200);

    Intent mus = new Intent (this, Music.class);
    startActivity(mus);
 }

// handler for home button used on all screens
public void BackButton (View view) {

    MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
    mMediaPlayer.start();

    Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vib.vibrate(200);

    Intent mn = new Intent (this, Music.class);
    startActivity(mn);
 }

}

Its easy. Follow these steps :-

  1. Add a seek bar change Listener.

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {         
        int seeked_progess;
    
        @Override
        public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
    
            seeked_progess = progress;
            seeked_progess = seeked_progess * 1000;
    
            if (fromUser) {                 
            }
        }
    
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
    
        }
    
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
    
        }
    });
    
  2. Now in if(fromUser), U need to add the implementation.

      if (fromUser) {
    
                Runnable mRunnable = new Runnable() {
    
                    @Override
                    public void run() {
                        int min, sec;
    
                        if (mediaPlayer != null /*Checking if the
                           music player is null or not otherwise it
                           may throw an exception*/) {
                            int mCurrentPosition = seekBar.getProgress();
    
                            min = mCurrentPosition / 60;
                            sec = mCurrentPosition % 60;
    
                            Log.e("Music Player Activity", "Minutes : "+min +" Seconds : " + sec);
    
                            /*currentime_mm.setText("" + min);
                            currentime_ss.setText("" + sec);*/
                        }
                        mHandler.postDelayed(this, 1000);
                    }
                };
                mRunnable.run();}
    
  3. At last add this in onStopTrackingTouch()

    @Override
     public void onStopTrackingTouch(SeekBar seekBar) {
         mediaPlayer.seekTo(seeked_progess);
        }
    });
    

Note :-

mHandler in a global variable. Initialize it as follows.

Handler mHandler = new Handler();

Secondly currentime_mm and currentime_ss are text views which display the current seek time of the seek bar.

and most Important, dont forgot to add these when a song starts

seekBar.setProgress(0);// To set initial progress, i.e zero in starting of the song
seekBar.setMax(mediaDuration);// To set the max progress, i.e duration of the song

Android Building Audio Player Tutorial, Tutorial about building an audio player in android. A simple for SeekBar. In this tutorial i used customized SeekBar to show song progress. To fix error simply add final String MEDIA_PATH = new String(Environment. 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.

Put this code inside onCreate() method

     seekbar.setMax(mediaPlayer.getDuration());
     seekbar.setProgress(mediaPlayer.getCurrentPosition());
    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run()
        {
             seekbar.setProgress(mediaPlayer.getCurrentPosition());
        }
    },0,1000);
     seekbar.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) {

        }
    });

A Step by Step Guide to Building an Android Audio Player App , Replace the original methods in the Service template with the following. @​Override public void onCompletion(MediaPlayer mp) { //Invoked when  How to play Audio Files in Android with a SeekBar feature and MediaPlayer class In this tutorial we will explain how to play Audio files in Android using MediaPlayer class. 0

What Punam did is good but add a condition in your "onProgressChanged" function like this:

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

Android tutorial 4: A basic media player - GStreamer, We only need to replace the manual pipeline we used in Android tutorial 3: We will add a Seek Bar, with a moving thumb that will advance as our current  Another solid choice for an Android music player is JetAudio HD Player Plus, a premium music player that plays a variety of file formats stored locally or in your network folders over Wi-Fi.

SeekBar.OnSeekBarChangeListener, (The default values for min is 0 and max is 100.) fromUser, boolean : True if the progress change was initiated by the user. Step Four – Handling Audio Focus. For a good user experience with audio in Android, you need to be careful that your app plays nicely with the system and other apps that also play media.

Seekbar android event, A couple of years ago, I posted an Android SeekBar preference widget that I'd written. new to Android development, and have been tasked with fixing an existing This is how we run a simple seek bar implementation for the music player. Discuss: 15 common Android problems and how to fix them Sign in to comment. Be respectful, keep it civil and stay on topic. We delete comments that violate our policy, which we encourage you to

Playback position regularly moves back to pre-last position after , Often, but I can't tell in which cases exactly, the playback position of an item My quick-fix is to pay attention to the position when I hit play, so that I can The seekbar moves back from original position (at which I paused) to actual Seeking is asynchronous, so when Android is told to play the audio file  HikiPlayer is a lightweight folder based music player. Features: - Loading album arts from internet (Pro version) - Customizable text, background, icon and widget color - Customizable font, icon and seekbar size - Skins (embedded and custom) - Updating UI colors from album art image - Embedded and external album art (cover.jpg, front.jpg etc.) - Local lyrics search by tags - СUE sheet - RTL

Comments
  • Thanks for the reply but I have not been able to implement the solution properly. Maybe I'm putting the code in the wrong places!?
  • No problem.. lets go step by step... have u implemented the first step ?
  • Thanks. I think I have the first part ok. Ive put in within the onCreate method and changed seekBar on the first line to seekbar as eclipse didnt like 'seekBar'
  • reason for eclipse to not recognise the "seekBar" is that you have defined the varibale "seekbar" in your code. But thats not the problem. You can put the first step in onCreate(). Now coming to second step.
  • Let me change the code and make it specific to your app.