SoundPool没有播放声音(而MediaPlayer则播放声音)

问题描述 投票:0回答:1

我想在应用程序中播放声音。但是,使用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();
}
android audio soundpool
1个回答
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);
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.