1

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?

Stef
  • 644
  • 1
  • 8
  • 25

1 Answers1

1

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);
stamanuel
  • 3,731
  • 1
  • 30
  • 45
  • Can you please tell me what the "context" is? Is it somehow related to the name of my MainActivity ? – Stef Feb 14 '14 at 11:34
  • 1
    simply said: [what is a context](http://stackoverflow.com/questions/3572463/what-is-context-in-android) .if you are inside an activity you can just use "this" or "getContext()" as context, if you move it to some other class you have to pass the context of the calling activity (this is necessary to for example have access to the resources) – stamanuel Feb 14 '14 at 11:38
  • Thanks a lot! That did the trick. Now I just have to stop the playback of the soundpool, whenever a button is pressed. – Stef Feb 14 '14 at 11:50
  • The Soundboard is now working, but all the sounds stop after more or less 6 seconds. After some research, I came to this website http://ignoranceisfutile.com/node/49 Here it says that the soundfile needs to be of .ogg-format, with a specific bit-and samplerate. Is there a way to keep playing Mp3-files? – Stef Feb 14 '14 at 18:49
  • Found a similar question: http://stackoverflow.com/questions/13377604/soundpool-plays-only-first-5-secs-of-file-why – Stef Feb 14 '14 at 18:51