I am trying to play a song by using seek bar listener. But when I try to drag the progress bar then it is playing from beginning of the song. It need to play from that dragged position.
Here is my code:
public class MainActivity extends Activity {
private TextView prairText;
private AssetFileDescriptor descriptor;
private SeekBar seekBar;
private MediaPlayer mp = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen active
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
init();
// Play prayer
/*if (mp != null) {
mp.start();
}*/
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mp != null && fromUser) {
mp.seekTo(progress * 1000);
}
}
});
findViewById(R.id.play_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mp != null) {
mp.start();
final Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mp != null){
int mCurrentPosition = mp.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.pauseButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mp != null) {
mp.pause();
findViewById(R.id.pauseButton).setVisibility(View.INVISIBLE);
findViewById(R.id.play_button).setVisibility(View.VISIBLE);
}
mp.pause();
}
});
findViewById(R.id.restart_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mp != null) {
mp.seekTo(0);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
private void init() {
prairText = (TextView) findViewById(R.id.prairText);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
try {
descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
seekBar.setMax(mp.getDuration());
}
How to resolve this issue. Thanks in advance..