Reputation: 289
I am trying to write a simple Android MediaPlayer code. I am facing an issue while stopping a song and restart again. In each button click. Otherwise , if i wont stop the track then , in each button click the song is not playing , it wait until the songs stops.
My requirement is , in each button click the song should start from the beginning.
MyCode:
package com.example.musicexample;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button btnPlay;
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(mPlayer.isPlaying()){
mPlayer.stop();
mPlayer.reset();
}
mPlayer.start();
}
});
} }
In the above code , the song plays once then , it won't play again.
So please go through it , please let me know , how can i stop the track if the song is playing and then restart it from beginning.
Upvotes: 0
Views: 2307
Reputation: 707
You can try this:
MediaPlayer m1 = null;
play1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
m1=MediaPlayer.create(MainActivity.this, R.raw.a);
m1.start();
}
});
private void stopPlaying() {
if (mp1 != null) {
m1.stop();
m1.release();
m1 = null;
}
Upvotes: 1
Reputation: 24998
You are calling the reset()
method which returns the MediaPlayer
to its un-initialized state.
Resets the MediaPlayer to its uninitialized state.
You will have to set the source of the MediaPlayer
once again to get it to play.
Upvotes: 0
Reputation: 571
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
http://developer.android.com/reference/android/media/MediaPlayer.html
Upvotes: 0