java - 如何使用 SoundPool 播放随机声音?

标签 java android audio playback soundpool

How to make Random sound when button click?

我对编程世界很陌生,我之前检查过上面的链接,尝试使用它作为播放随机声音的引用。我使用 SoundPool 是因为我知道它比 MediaPlayer 更适合播放短片。我总共有四种声音。

当我运行我的应用程序时,我收到一条错误消息,表示不幸的是它已停止。

对于可能出现的问题有什么想法吗?

这是我的代码:

import java.util.Random;

public class actibida extends AppCompatActivity {
SoundPool soundPool;
Button button;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_actibida);

    final int[] sound = new int[4];
    sound[0] = soundPool.load(actibida.this, R.raw.el, 1);
    sound[1] = soundPool.load(actibida.this, R.raw.guau, 1);
    sound[2] = soundPool.load(actibida.this, R.raw.miau, 1);
    sound[3] = soundPool.load(actibida.this, R.raw.quack, 1);

    final Random r = new Random();

    button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View button) {
            soundPool.play(sound[r.nextInt(4)], 1.0f, 1.0f, 0, 0, 1.0f);
        }

    });
}

}

最佳答案

您实际上尚未创建要使用的 SoundPool 实例。在调用 soundPool.load 之前,您必须使用 the SoundPool constructor (或 Builder API)来创建定义 SoundPool 某些属性的实例。

关于java - 如何使用 SoundPool 播放随机声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393846/

相关文章:

java - 太多的 SQL 变量和 NOT IN 子句

Android 自适应 ImageView 尺寸到屏幕尺寸

php - 在网站 : Red5 stream or posting the audio data? 上录制音频

javascript - 如何在不扩展的情况下播放音频

audio - 数据网络(3G)上的 Asterisk 中没有音频

java - 使用 Java 帮助现实世界的 TDD

java - HttpURLConnection getInputStream() 有时包含响应头

java - 如果数组未排序,则 binarySearch 返回一个随机索引;返回索引背后的逻辑是什么?

java - 如何将参数发送到包含的组件?

android - Android 10 上的自定义通知中没有展开按钮