MediaPlayer is a state machine, here's the Doc .
So, first thing, read the doc, the state diagram says: release() => end.
So if you want to control the same track with different buttons do not call release();
and do set set mp = null;
between your cases.
Dhaval has given you the right solution:
if (mp.isPlaying()) {
mp.pause()
} else {
mp.play()
}
Also, in order to properly release the player, call first reset() then release() or you'll get a warning saying " the player went awaing with unhandled events.." or something like that.
Please make sure you understand the state diagram and it wiil work like a charm :)
To Sum up:
Read the doc :)
Check the play state of the player
Remove the unnecessary calls to release()
- Release the player properly once you're done
Hope this helps!
Edit: Okay so here's what I'd do: (It might not compile, I only have a text editor here so sorry^^)
In your activity(I suppose): Your activity must implement the onPreparedListener
@Override
onCreate() {
if(mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer()
mMediaPlayer.setOnPreparedListener(this); //registers your activity as the onPrepared Listener
}
...
}
//Called back when media is ready to be played
@Override
onPrepared() {
if(mMediaPlayer != null){
mMediaPlayer.start();
}
}
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
..
break;
case 1:
if(mMediaPlayer.isPlaying() {
mMediaPlayer.pause();
} else {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(Sadrzaj.this, R.raw.s16dance);
mMediaPlayer.prepareAsync();//call back onPrepared()
//mMediaPlayer.start(); sorry little mistake here no need to call start(); since it is called in onPrepared()
}
break;
default:
if(mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
break;
}
}
//Release the player and de listener
@Override
onDestroy() {
if(mMediaPlayer != null) {
mMediaPlayer.setOnPreparedListener(null);
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null
}
}