簡體   English   中英

SoundPool沒有播放聲音(而MediaPlayer則播放聲音)

[英]SoundPool not playing sound (while MediaPlayer does)

我想在應用程序中播放聲音。 但是,使用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();
}

解決了!

我錯過了等待聲音文件加載到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);
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM