Skip to content Skip to sidebar Skip to footer

How To Make Random Sound When Button Click?

So i have 4 sound here, i was use SoundPool sound1 = soundPool.load(this, R.raw.aww, 1); sound2 = soundPool.load(this, R.raw.arh, 1); sound3 = soundPool.load(this, R

Solution 1:

You can store soundIDs in an array and select one of them randomly with Random class of Java.

int[] sound = newint[4];
sound[0] = soundPool.load(this, R.raw.aww, 1);
sound[1] = soundPool.load(this, R.raw.arh, 1);
sound[2] = soundPool.load(this, R.raw.agg, 1);
sound[3] = soundPool.load(this, R.raw.uhh, 1);

Random random = new Random();

click = (Button) findViewById(R.id.bm);
click.setOnClickListener(new View.OnClickListener() {
    publicvoidonClick(View click) {
        //choose one of four sound to play
        soundPool.play(sound[random.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f);
    }
});

Solution 2:

How about putting a reference to each of the sounds in an array? Then you can generate a random number between 0 and array.length-1 and play that sound.

Solution 3:

Assuming you have N sound clips

int[] sounds={sound1, sound2,.........., soundN};

get them play randomly on click of button

 Random r =new Random();
 intstart=0;
 intend= N;
 int playRandom = r.nextInt(end-start) +start; 
 player = MediaPlayer.create(getApplicationContext(),sounds[playRandom]);
 player.start();

Post a Comment for "How To Make Random Sound When Button Click?"