I have a SeekBar
, it displays correctly MediaPlayer
progress. However, I have troubles with seeking - if I seek scroll box somewhere it just return
I am using this simple code to do the trick.
package in.bhartisoftwares.amit.allamitapps;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class audioControllerTwo extends AppCompatActivity {
MediaPlayer mPlayer;
SeekBar audioTraverse;
here I have defined My SeekBar and MediaPlayer in public class. Then on OnCreate Method I have code like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_controller_two);
mPlayer = MediaPlayer.create(this, R.raw.song);
Here I am creating mPlayer variable, that finds my audio file called "song" which is present in "raw" folder.
Then I grabbed my SeekBar called "audioTraverse" and assigned it to "audioTraverse" variable and grabbing the "Duration" of audio file and assigning that duration to my "audioTraverse" SeekBar as follows:
audioTraverse = (SeekBar) findViewById(R.id.audioTraverse);
audioTraverse.setMax(mPlayer.getDuration());
Now I am running a timer that will run after every second and it will update the SeekBar position accordingly. See the code below:
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
audioTraverse.setProgress(mPlayer.getCurrentPosition());
}
},0, 1000); // here 0 represents first time this timer will run... In this case it will run after 0 seconds after activity is launched
// And 1000 represents the time interval afer which this thread i.e., "run()" will execute. In this case, it will execute after every 1 second
Now I am adding "SeekBarChangeListener", this will look for any changes on SeekBar and in "OnProgressChange()" method I am using ".seekTo()" method to go to a particular duration in audio file. Code is as follows:
audioTraverse.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
Log.i("Tranverse Change: ", Integer.toString(i));
mPlayer.seekTo(i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}