SoundPool无法播放声音(MediaPlayer却可以)

时间:2019-03-16 19:42:32

标签: android audio soundpool

我正在尝试在应用程序中播放声音。但是,我无法使用SoundPool。代码真的很简单,我看不出它会失败。

类似的代码,但是使用MediaPlayer确实可以,但是我对使用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();
}

1 个答案:

答案 0 :(得分:0)

解决了!

我没有等待将声音文件加载到soundPool中。正确的代码是:

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);
        }
    });
}
相关问题