SoundPool无法播放声音(而MediaPlayer却可以) [英] SoundPool not playing sound (while MediaPlayer does)
本文介绍了SoundPool无法播放声音(而MediaPlayer却可以)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在应用程序中播放声音.但是,使用SoundPool无法做到这一点.代码真的很简单,我看不出它会在哪里失败.
I am trying to play a sound in an app. However, using SoundPool I am unable to do so. The code is really simple and I don't see where it can fail.
类似的代码,但是使用MediaPlayer确实可以,但是我对使用SoundPool感兴趣.
A similar code but using MediaPlayer does work, but I am interested in using SoundPool.
SoundPool代码:
private void playSound2(){
SoundPool sp = new SoundPool.Builder().build();
int soundID = sp.load(MainActivity.this, R.raw.sound, 1);
sp.play(soundID, 1, 1, 1, 0, 1);
}
上下文:
public void goButtonClick(View view){
Button goButton = findViewById(id.button2);
if (onGoing){
goButton.setText("GO!");
} else {
goButton.setText("STOP");
//playSound(); // MediaPlayer
playSound2(); // SoundPool
}
onGoing = !onGoing;
}
MediaPlayer版本(有效):
private void playSound(){
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.sound);
mediaPlayer.start();
}
推荐答案
已解决!
我没有等待将声音文件加载到soundPool中.正确的代码是:
I was missing to wait for the loading of the sound file into soundPool. The correct code is:
private void playSound2() {
SoundPool sp = new SoundPool.Builder().build();
int soundID = sp.load(MainActivity.this, raw.sound, 1);
sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool sp, int soundID, int i1) {
sp.play(soundID, 1, 1, 1, 0, 1);
}
});
}
这篇关于SoundPool无法播放声音(而MediaPlayer却可以)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文