I am trying to write an Android Soundboard with multiple buttons. Each button should play a different sound.
I have a OnClickListener on each button:
buttonAlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playSound("alan");
}
});
Each of these buttons is calling the following function.
private void playSound(String sound) {
int path = getResources().getIdentifier(sound, "raw", getPackageName());
mediaplayer = MediaPlayer.create(this, path);
try {
mediaplayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaplayer.start();
}
The soundboard works, but everytime you click a button it plays the sound over and over again. I need the mediaplayer to stop playing, but everytime I write something like mediaplayer.stop(), the App won't work at all. Any suggestions what I should change in my function/code?
i solved it using a soundpool, there you can also play multiple sounds at the same time. i first initialize it and load sounds i need in the constructor
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
int gameOverSound = soundPool.load(context, R.raw.gameover, 1);
and then you can play it like this:
public void playSound(int soundId) {
soundPool.play(soundId, 1.0f, 1.0f, 0, 0, 1);
}
edit: regarding the mediaplayer you have to call stop() and release() before you start playing another sound. also you can set
mPlayer.setLooping(false);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.