android-studio - 从阵列中选择随机声音以在Android Studio上单击按钮播放

标签 android-studio audio random

我想从阵列中选择随机声音

<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/

相关文章:

android - 为什么我的项目会在我的手机上运行而不是我的 AVD?

javascript - 如何将 HTMLAudioElement 当前播放位置重置为 0?

algorithm - 在矩形区域内均匀生成一个随机点(一些矩形可能重叠)

python - 如何在 python 中创建一个以随机字母作为键且没有重复项的字典?

java - 尝试从另一个类的随机数中打印出数组

android-studio - Gradle 同步失败 Android Studio 3.6

java - 如何在 android studio 中使用我的应用程序在字符串数组中添加更多字符串

java - 如何在 Android Studio 中从 pdf 或 excel 文件导入联系号码?

ios - AVAudioPlayer 为音频文件返回错误的持续时间

c++ - 将数据从一个 AudioSampleBuffer 复制到不同类中的另一个