How to make Random sound when button click?

[亡魂溺海] 提交于 2019-12-13 21:05:18

问题


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.raw.agg, 1);
     sound4 = soundPool.load(this, R.raw.uhh, 1);

so i wonder how to make button choose random sound :

    click= (Button)findViewById(R.id.bm);
    click.setOnClickListener(new View.OnClickListener() {

          public void onClick(View click){             
             //choose one of four sound to play   
            }
        });
}

Anyone have some Idea?


回答1:


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

int[] sound = new int[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() {
    public void onClick(View click) {
        //choose one of four sound to play
        soundPool.play(sound[random.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f);
    }
});



回答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.




回答3:


Assuming you have N sound clips

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

get them play randomly on click of button

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


来源:https://stackoverflow.com/questions/33960918/how-to-make-random-sound-when-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!