如何在按钮点击时发出随机声音?

时间:2015-11-27 15:52:53

标签: java android button random soundpool

所以我这里有4个声音,我使用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);

所以我想知道如何让按钮选择随机声音:

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

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

任何人都有一些想法?

3 个答案:

答案 0 :(得分:2)

您可以将soundID存储在数组中,并使用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);
    }
});

答案 1 :(得分:0)

如何对数组中的每个声音进行引用?然后你可以生成一个介于0和array.length-1之间的随机数并播放那个声音。

答案 2 :(得分:0)

假设您有N个声音片段

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

点击按钮

随机播放
 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();