我想从阵列中选择随机声音
<array name="cat_sounds">
<item>@raw/cat_1</item>
<item>@raw/cat_2</item>
<item>@raw/cat_3</item>
</array>
并在单击按钮时播放声音。
//Cat button sounds
TypedArray cat_sounds = getResources().obtainTypedArray(R.array.cat_sounds);
int choice = (int) (Math.random() * cat_sounds.length());
Button cat = (Button) this.findViewById(R.id.catSounds);
final MediaPlayer mp = MediaPlayer.create(this,cat_sounds[choice]);
cat.setOnClickListener(new OnClickListener() {
public void onClick(View v){
mp.start();
}
});
但是由于某种原因,我的代码使我的应用程序崩溃了。怎么了??
最佳答案
我设法使它起作用
//Cat button
Button cat = (Button) this.findViewById(R.id.catSounds);
cat.setOnClickListener(new OnClickListener() {
public void onClick(View v){
//Select random sound
String[] cat_sounds = getResources().getStringArray(R.array.cat_sounds);
String randomString = cat_sounds[new Random().nextInt(cat_sounds.length)];
int resID = getResources().getIdentifier(randomString, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), resID);
mp.start();
}
});
但是,每次单击后创建一个新的媒体播放器会导致20-30次单击后声音停止工作。有什么建议吗?
关于android-studio - 从阵列中选择随机声音以在Android Studio上单击按钮播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42912739/