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/