Reputation: 140
I'm building a thug life sound effect player and I wanted to know how can I stop the MediaPlayer from playing 2 or more tracks the same time.
This is the method that's called when a button is clicked:
int sequence = 1;
public void thugPlay (View view) {
// assign a media player to an audio file
MediaPlayer nothingButThatGthang = MediaPlayer.create(MainActivity.this, R.raw.g_thang);
MediaPlayer nextEpisode = MediaPlayer.create(MainActivity.this, R.raw.next_episode);
MediaPlayer fuckThePolice = MediaPlayer.create(MainActivity.this, R.raw.ftp);
MediaPlayer hipnotize = MediaPlayer.create(MainActivity.this, R.raw.hipnotize);
MediaPlayer moveBitch = MediaPlayer.create(MainActivity.this, R.raw.move_bitch);
MediaPlayer ridin = MediaPlayer.create(MainActivity.this, R.raw.ridin);
MediaPlayer still = MediaPlayer.create(MainActivity.this, R.raw.still);
// Plays according to sequence's value
if (sequence == 1) {
still.stop();
nothingButThatGthang.start();
sequence++ ;
}
else if (sequence == 2) {
nothingButThatGthang.stop();
nextEpisode.start();
sequence++ ;
}
else if (sequence == 3) {
nextEpisode.stop();
fuckThePolice.start();
sequence++ ;
}
else if (sequence == 4) {
fuckThePolice.stop();
hipnotize.start();
sequence++ ;
}
else if (sequence == 5) {
hipnotize.stop();
moveBitch.start();
sequence++ ;
}
else if (sequence == 6) {
moveBitch.stop();
ridin.start();
sequence++ ;
}
else {
ridin.stop();
still.start();
sequence = 1 ;
}
}
As you can see, before playing the current audio file it should stop the previous one, however, it doesn't happen.
Thank you!
Upvotes: 2
Views: 1665
Reputation: 7674
Create one MediaPlayer variable as class member:
MediaPlayer mp;
Then in your click event:
if (mp != null && mp.isPlaying()){
mp.stop();
}
if (sequence == 1) {
mp = MediaPlayer.create(MainActivity.this, R.raw.still);
mp.start();
sequence++;
}
You should off-course complete the If statment.
Upvotes: 2