In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button. I want to pause the playback by clicking the same button again.ie) single button for play/pause. How shall i do this.
public class MainActivity extends AppCompatActivity {
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file) final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
}
You could use simple if-check to handle the pausing. Try this:
Inside the button click check for
mediaPlayer.isPlaying()
. This will return true if the media player is playing else false.So now with this, flag value you can make a if statement and switch to play or pause like this,
Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using
mediaplayer class
, so you might find it a bit primitive. However if you need you can also check out theVideoView
examples. It's apparently easier withVideoView
as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.For pausing the
Mediaplayer
:and for resuming the player from the position where it stopped lately is done by: