Reputation: 3
I have a problem with my soundboard app for android. When I test it on my device, the app crashes when I press the 8th ImageButton :. Besides that I am wondering how I can stop the mediaplayer when I press another button. Here is my code:
package nl.ingmar.soundboard;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class Main extends Activity implements OnClickListener {
ImageButton[] imagebuttons = new ImageButton[20];
MediaPlayer[] geluiden = new MediaPlayer[20];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
for(int i=0; i<geluiden.length; i++){
int rawID = getResources().getIdentifier( "geluid" + (i+1) , "raw" , getPackageName() );
int resID = getResources().getIdentifier("btn" + (i+1), "id", getPackageName());
imagebuttons[i] = ((ImageButton) findViewById(resID));
imagebuttons[i].setOnClickListener(this);
geluiden[i] = MediaPlayer.create(this, rawID);
}
}
@Override
public void onClick(View v) {
int index = 0;
for(int i = 0; i<imagebuttons.length; i++){
if(imagebuttons[i].getId() == v.getId()){
index = i;
geluiden[i].start();
}
}
}
}
Upvotes: 0
Views: 1025
Reputation: 8079
I suggest you not use so many nediaplayer instances... there is a chance that you may get Mediaplayer error (-19,0) error because of non availability of resources.. so instead use a single mediapleyer instead of an array of mediaplayers.. in onclick create the mediaplayer and start .. check if mediaplayer is playing..
public void onClick(View v) {
....
if(geluiden.isplaying()){
geluiden.stop();
//create mediaplayer player with new resource and start..
}
Upvotes: 0
Reputation: 14038
Using so many MediaPlayer instances is a bad idea. My guess is that creating these many instances is giving you the error.You are not releasing the mediaplayers you are using to play the sound by calling release()
and you soon get out of memory. Call geluiden[i].release() on every instance when done.
I would also like to tell you that MediaPlayer is not a good option when you are playing small sound effects as the user can click on multiple buttons very soon and you will have to create a MP object for all of them which doesnt happen synchronously. . Go for the SoundPool Class which allows you to keep smaller sounds loaded in memory and you can play them any time you want without any lag which you would feel in a mediaplayer. http://developer.android.com/reference/android/media/SoundPool.html Here is a nice tutorial : http://www.anddev.org/using_soundpool_instead_of_mediaplayer-t3115.html
Upvotes: 2