0

I'm trying to create a simple audio player, but when i'm applying a timer to a seekbar for updating it a song starting to lag. Here's the code:

    final SeekBar playProgress = findViewById(R.id.playProgress);
    playProgress.setMax(mPlayer.getDuration());

    //++++++++Lagging++++++++++++
    new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run () {
                playProgress.setProgress(mPlayer.getCurrentPosition());
            }
    },0,1000);
    //+++++++++++++++++++++++++++

    playProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()

        {
            @Override
            public void onProgressChanged (SeekBar seekBar,int i, boolean b){
            mPlayer.seekTo(i);
        });
fxvlad
  • 129
  • 2
  • 3
  • 9

3 Answers3

0

Your timer is running every 1000 milliseconds, and changing the progress of the playProgress to the current position. Everytime the progress is changed (onProgressChanged) you are executing a seekTo() to the seekbar's new position, which could induce the lag.

The onProgressChanged signature looks like this: onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) - try only executing the seekTo method if the fromUser variable is true, which would mean that you did not set the progress programmatically (which you are doing in your timer).

damian
  • 2,001
  • 20
  • 38
0

Replace: mPlayer.seekTo(i); By: if(b){ mPlayer.seekTo(i); }// so that this codes executes only when the user is changing it

0

Try this, it has worked for me.

myViewHolder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                            // Update the progress depending on seek bar
                            if (fromUser) {
                                mediaPlayer.seekTo(progress);//if user drags the seekbar, it gets the position and updates in textView.
                            }
                            final long mMinutes = (progress / 1000) / 60;//converting into minutes
                            final int mSeconds = ((progress / 1000) % 60);//converting into seconds
                            myViewHolder.desc.setText(mMinutes + ":" + mSeconds);


                        }