SoundPool not playing sound (while MediaPlayer does)

百般思念 提交于 2021-02-05 11:24:23

问题


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.

A similar code but using MediaPlayer does work, but I am interested in using SoundPool.

SoundPool code:

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);
}

Context:

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 version (works):

private void playSound(){
    MediaPlayer mediaPlayer;
    mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.sound);
    mediaPlayer.start();
}

回答1:


Solved!

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);
        }
    });
}


来源:https://stackoverflow.com/questions/55200787/soundpool-not-playing-sound-while-mediaplayer-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!