声音池崩溃

时间:2011-10-06 15:53:23

标签: android

当用户按下按钮时,我使用声音池播放声音。按下一些按钮后,应用程序强制关闭。正在播放的声音只有几秒钟。有没有更好的方法来实现音频?

我使用这个类:

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();

}

}

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试在加载声音之前播放声音。 SoundPool.load方法不同步。因此,如果您致电

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

您将在运行时崩溃100%。 仅应在调用onLoadComplete之后调用play():

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