Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 SoundPool 音效無法播放(soundpool 1 not retry)問題

編輯:關於 Android 程式設計

開發中用到 SoundPool 播放音效時,遇到了 "soundpool 1 not retry" 的報錯,聲音遲遲無法播放,而改用 MediaPlayer 卻能正常發聲。經過一番排查,終於定位到了原因。

問題代碼

下面這段代碼會出現 "soundpool 1 not retry",且無法播放聲音:

mgr = (AudioManager) MainActivity.this.getSystemService(Context.AUDIO_SERVICE);
// 初始化 soundPool:參數1 最大同時播放的聲音流數,參數2 聲音類型,參數3 品質
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(1, soundPool.load(MainActivity.this, R.raw.or, 1));
soundPoolMap.put(2, soundPool.load(MainActivity.this, R.raw.sd, 1));
volume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
// loop:循環模式(0 = 不循環,-1 = 無限循環)
soundPool.play(soundPoolMap.get(1), volume, volume, 1, 0, 1f);

原因剖析

問題出在 load() 之後立刻 play():soundPool.load() 是異步的,系統尚未把聲音文件準備好就調用 play(),自然無法播放,於是拋出 "not retry"。

解決方案

思路是「先 load、後 play」,中間留出足夠時間讓系統完成加載。比如在初始化時就 load 好,等真正需要播放時再 play;或者在 load 之後稍作等待:

mgr = (AudioManager) MainActivity.this.getSystemService(Context.AUDIO_SERVICE);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(1, soundPool.load(MainActivity.this, R.raw.or, 1));
soundPoolMap.put(2, soundPool.load(MainActivity.this, R.raw.sd, 1));
volume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
soundPool.play(soundPoolMap.get(1), volume, volume, 1, 0, 1f);

更規範的做法是使用 SoundPool 提供的 setOnLoadCompleteListener 監聽加載完成事件,在回調裡再觸發 play,這樣既不用硬等待,也能確保音效一定準備就緒,是比 Thread.sleep 更可靠的方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved