在公司產(chǎn)品中需求在設(shè)備后臺收集到數(shù)據(jù)的時候一直嘀嘀嘀,獲取到目標是發(fā)出警報聲,設(shè)備斷鏈時警告,于是就用上SoundPool,但是在使用的過程中發(fā)現(xiàn)了兩個神坑,終于在經(jīng)過各種折騰之后得到解決:
1.加載完成后沒有聲音
理所應(yīng)當?shù)膶懥诉@么一段,結(jié)果卻發(fā)現(xiàn)什么鬼調(diào)用后不會響
@Override
public void speak(Object content) {
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_ALARM, 5);
int soundID = soundPool.load(CrashApplication.getContext(), (Integer) content, Integer.MAX_VALUE);
soundPool.play(soundID, 0.6f, 0.6f, 1, 0, 1);
}
這個原因嗎是因為在
int soundID = soundPool.load(CrashApplication.getContext(), (Integer) content, Integer.MAX_VALUE);
這一句下邊的play可能在load完成之前執(zhí)行,但這是得到的soundId是空的.,所以當然沒有聲音了,解決辦法是,SoundPool提供了一個監(jiān)聽加載資源完成的回調(diào)public void setOnLoadCompleteListener(OnLoadCompleteListener listener)只需要在這個回調(diào)中播放聲音就好啦:
@Override
public void speak(Object content) {
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_ALARM, 5);
final int soundID = soundPool.load(CrashApplication.getContext(), (Integer) content, Integer.MAX_VALUE);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
soundPool.play(soundID, 0.6f, 0.6f, 1, 0, 1);
}
});
}
2.第二次以后調(diào)用stop/pause停不下來
這個問題的坑在于每次播放soundPool.play(soundID, 0.6f, 0.6f, 1, 0, 1);以后,那個soudId就會改變,點開play方法一看:
` public final int play(int soundID, float leftVolume, float rightVolume,int priority, int loop, float rate)`
嘗試重新聲明一個變量playId 來存放返回值
playId = soundPool.play(ringId, 0.1f, 0.1f, 1, -1, 1);
在需要暫停的時候傳這個playId:
問題解決!
但是谷歌為毛設(shè)計成頻繁的更換soundId?之前的好像也沒被回收,因為在執(zhí)行resume方法的時候我回傳了load出來的Id,還是能夠正常播放,請知道的大神指導(dǎo)一下啊...