Reputation: 315
I have a soundboard, everything works fine but when I click alot on the buttons after a while the sound just stopped be played .. this is the code :
public class MainActivity extends AppCompatActivity{
//Sounds/Remixes MediaPlayer
MediaPlayer sound1, sound2, sound3, sound4, remix1, remix2, remix3, remix4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Sound MediaPlayers
sound1= MediaPlayer.create(this, R.raw.sound1);
sound2= MediaPlayer.create(this, R.raw.sound2);
sound3= MediaPlayer.create(this, R.raw.sound3);
sound4= MediaPlayer.create(this, R.raw.sound4);
//Remixes MediaPlayer
remix1= MediaPlayer.create(this, R.raw.remix1);
remix2= MediaPlayer.create(this, R.raw.remix2);
remix3= MediaPlayer.create(this, R.raw.remix3);
remix4= MediaPlayer.create(this, R.raw.remix4);
}
//Songs stop playing when closing/switching the App
@Override
protected void onPause() {
remix1.pause();
remix2.pause();
remix3.pause();
remix4.pause();
super.onPause();
}
//Remix onClick's
public void remix1(View view){
if(remix1.isPlaying() == true){
remix1.pause();
}else{
remix1.start();
}
}
public void remix2(View view){
if(remix2.isPlaying() == true){
remix2.pause();
}else{
remix2.start();
}
}
public void remix3(View view){
if(remix3.isPlaying() == true){
remix3.pause();
}else{
remix3.start();
}
}
public void remix4(View view){
if(remix4.isPlaying() == true){
remix4.pause();
}else{
remix4.start();
}
}
//sound onClick's
public void sound1(View view){
sound1.start();
}
public void sound2(View view){
sound2.start();
}
public void sound3(View view){
sound3.start();
}
public void sound4(View view){
sound4.start();
}
}
This is my code with only 4 sounds and 4 remixes.
The sounds are 3 seconds long and the remixes 3 Minutes.
This is my app, you can try it and you'll see sometime the buttons stop working: https://play.google.com/store/apps/details?id=com.aaron.waller.angelasoundboard
The only solution i found was to clean up the MediaPlayer after each use, how can i do that?
Upvotes: 0
Views: 2527
Reputation: 6592
To clean up media player after each use you should call
mediaPlayer.release();
But if everything you need is just return mediaPlayer to its state right after create
method
mediaPlayer.reset();
should be enough
UPD
In your case add this code to onCreate
for every mediaPlayer you use.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.reset();
//if reset doesnt give you what you need use mp.release() instead
//but dont forget to call MediaPlayer.create
//before next mediaPlayer.start() method
}
});
Upvotes: 4