Search code examples
javaandroidaudioplaybacksoundpool

How to play a random sound using SoundPool?


How to make Random sound when button click?

I'm quite new to the programming world and I had previously checked the above link to try and use it as a reference to play a random sound. I'm using SoundPool since I understand that it's better at playing short clips than MediaPlayer. I have a total of four sounds.

When I run my app, I get an error saying that unfortunately it has stopped.

Any ideas on what could be possibly wrong?

This is my code:

import java.util.Random;

public class actibida extends AppCompatActivity {
SoundPool soundPool;
Button button;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_actibida);

    final int[] sound = new int[4];
    sound[0] = soundPool.load(actibida.this, R.raw.el, 1);
    sound[1] = soundPool.load(actibida.this, R.raw.guau, 1);
    sound[2] = soundPool.load(actibida.this, R.raw.miau, 1);
    sound[3] = soundPool.load(actibida.this, R.raw.quack, 1);

    final Random r = new Random();

    button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View button) {
            soundPool.play(sound[r.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f);
        }

    });
}

}


Solution

  • You haven't actually created an instance of SoundPool to work with. Before you call soundPool.load, you will have to use the SoundPool constructor (or the Builder API) to create an instance that defines some properties of the SoundPool.