簡體   English   中英

Android:在SoundPool中無限播放聲音在停止后第二次播放

[英]Android: Playing sound infinitely in SoundPool doesn't play for the second time after stop

我試圖通過SoundPool播放2個聲音。

以下測試代碼使第二次播放沒有聲音。 只有當我在HTC Hero設備和模擬器上播放無限聲音時才會出現這種情況。 我使用的是Android 1.6。

...
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
int soundId1 = soundPool.load(getApplicationContext(), R.raw.sound1, 1);
int soundId2 = soundPool.load(getApplicationContext(), R.raw.sound2, 1);

// the first one plays
int streamId = soundPool.play(soundId1, 1.0f, 1.0f, 1, -1, 1.0f);
try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
soundPool.stop(streamId);

// the second one doesn't play
streamId = soundPool.play(soundId2, 1.0f, 1.0f, 1, -1, 1.0f);
try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
soundPool.stop(streamId);
...

在代碼中查看第一個聲音的這一行......

int streamId = soundPool.play(sound1, 1.0f, 1.0f, 1, -1, 1.0f);

根據此鏈接 ,第5個參數定義循環模式。 0表示無循環, -1表示循環永久。 你的代碼說-1 ,所以第一個聲音永遠循環,所以第二個聲音不會播放。 嘗試將第一個聲音的循環模式更改為無循環,即。 0。

編輯:我想我知道你的問題。 當您嘗試播放聲音時,樣本沒有准備好,因此,您需要實現onLoadCompleteListener,以便樣本在准備好時播放。 例。

SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                            int arg2) {
                streamId = soundPool.play(sampleId, 1.0f, 1.0f, 1, -1, 1.0f);
               }

        });
    int soundId1 = soundPool.load(getApplicationContext(), R.raw.tick, 1);      
    int soundId2 = soundPool.load(getApplicationContext(), R.raw.tock, 1);

加載這些聲音后,它們將被播放。 我測試了這個並且兩個聲音都播放,因為聽眾確保在播放之前加載它們。

將此代碼集成到您的代碼中,它應該可以解決問題。 如果沒有,請告訴我,我會嘗試找到另一個解決方案:)

暫無
暫無

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

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