How can I start the song from where I pressed pause button, help me out am new to media in android
and am unaware from the media properties all the buttons are working fine , but I want to start the song where from at which point I stopped it -
public class MainActivity extends Activity {
MediaPlayer mediaPlayer;
Button play, stop,pause;
Uri path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
path = Uri.parse("android.resource://" + getPackageName() + "/"+ R.raw.chelseafc);
mediaPlayer = MediaPlayer.create(MainActivity.this,path);
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
});
}
@Override
protected void onDestroy() {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
super.onDestroy();
}
}
Use following code -
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
mediaPlayer.start();
mediaPlayer.pause();
mediaPlayer.reset();
I think it will help you.
You have a start button, pause button and stop button. There is no Resume button. Also when you click start after pressing pause, media loads again and starts from beginning (length = 0). You have to seek it to the paused position and resume it :
Define a global variable :
int length = 0;
In pause listener:
length=mediaPlayer.getCurrentPosition();
In resume (create a resume listener):
mediaplayer.seekTo(length);
mediaPlayer.start();
UPDATE
Ideally pause and resume button would be same except you would toggle on-off with changing image resource between play and pause pngs and execute relevant code with help of a boolean variable :
In pause button listener:
if(play)
{
//paused
play =false;
pause.setImageResource(R.id.pause);
length=mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
}else {
//resumed
play = true;
pause.setImageResource(R.id.resume);
mediaplayer.seekTo(length);
mediaPlayer.start();
}
Correct wherever necessary I typed in the editor not in IDE.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.