I have this method to play an audio file with a button:
final MediaPlayer mediaplayer = MediaPlayer.create(
this,
Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.inro));
mediaplayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});
What I’m trying to do is, when the audio is playing and the user clicks the button again, the audio will pause, but when he clicks it again the audio will resume.
Updated
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_nav_back:
WWHApplication.getMapActivityIntance().getVideoLocationDB();
WWHApplication.getMapActivityIntance().initLocations();
if (category == 'f') {
if (WWHApplication.getFavoritesListActivityIntance() != null)
WWHApplication.getFavoritesListActivityIntance()
.loadListView();
}
finish();
break;
case R.id.btn_tool_audio:
final MediaPlayer mediaplayer = MediaPlayer.create(this,
Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.inro));
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
break;
The problem is you are trying to pause a audio inside on PreparedListener. IT doesn’t work that way. Do the same inside a button click event,
Prepared Listener gets called only when the source is ready and good to go with playing. It doesn’t ensure the play and pause of your MediaPlayer.