如何使用 SoundPool 播放随机声音?
How to play a random sound using SoundPool?
我是编程界的新手,我之前已经检查过上面的 link 以尝试将其用作播放随机声音的参考。我正在使用 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 (or the Builder API) 创建一个定义 SoundPool 某些属性的实例。
我是编程界的新手,我之前已经检查过上面的 link 以尝试将其用作播放随机声音的参考。我正在使用 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 (or the Builder API) 创建一个定义 SoundPool 某些属性的实例。