android 開發(fā)中sound pool 的兩個坑

在公司產(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)一下啊...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容