开发者

Sound Pool Crashing

I use sound pool to play a sound when a user presses a button. After a number of button presses the app force closes. The sound that is playing is only a few seconds long. Is there a better way to implement audio?

I use this class:

public class SoundManager {

private  SoundPool mSoundPool; 
private  HashMap<Integer, Integer> mSoundPoolMap; 
private  AudioManager  mAudioManager;
private  Context mContext;


public SoundManager()
{

}

public void initSounds(Context theContext) { 
     mContext = theContext;
     mSoundPool = new SoundPool(200, AudioManager.STREAM_MUSIC, 0); 
     mSoundPoolMap = new HashMap<Integer, Integer>(); 
     mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);         
} 

public void addSound(int Index,int SoundID)
{
    mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}

public void playSound(int index) { 

     int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     mSoundPool.play(mSoundPoolMap.get(index), streamVolume开发者_运维技巧, streamVolume, 1, 0, 1f); 
}

public void playLoopedSound(int index) { 

     int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f); 
}

public void clear(){

     mSoundPoolMap.clear();
     mSoundPool.release();

}

}


It seems you are trying to play sound before it is loaded. SoundPool.load method is not synchronous. So if you call

addSound(...);
playSound(..);

You will get 100% crash in runtime. You should invoke play() only after onLoadComplete is called:

public void addSound(int index, int soundResId) {
    soundPool.setOnLoadCompleteListener((sp, sampleId, status) -> {
        if (status == 1) {
            mSoundPoolMap.put(index, sampleId);
        }
    });
    soundPool.load(context, soundResId, 1);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜