【问题标题】:How to play a random sound using SoundPool?如何使用 SoundPool 播放随机声音?
【发布时间】:2016-04-04 02:46:47
【问题描述】:

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);
        }

    });
}

}

【问题讨论】:

    标签: java android audio playback soundpool


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!那真是个愚蠢的错误。问题解决了。
    • 很高兴为您提供帮助。请不要忘记接受这个答案作为正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2020-09-12
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多