在项目中需要播放很短而不一样的铃声,在网上找了很多资料,对于比较小的铃声都推荐是使用SoundPool来实现,因为SoundPool有以下优点:
1. SoundPool最大只能申请1M的内存空间,这就意味着我们只能用一些很短的声音片段,而不是用它来播放歌曲或者做游戏背景音乐。
2. SoundPool提供了pause和stop方法,但这些方法建议最好不要轻易使用,因为有些时候它们可能会使你的程序莫名其妙的终止。Android开发网建议使用这两个方法的时候尽可能多做测试工作,还有些朋友反映它们不会立即中止播放声音,而是把缓冲区里的数据播放完才会停下来,也许会多播放一秒钟。
3. SoundPool的效率问题。其实SoundPool的效率在这些播放类中算是很好的了,但是有的朋友在G1中测试它还是有100ms左右的延迟,这可能会影响用户体验。也许这不能管SoundPool本身,因为到了性能比较好的Droid中这个延迟就可以让人接受了。
初始化SoundPool:
- mSP = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
- mSPMap = new HashMap<Integer, Integer>();
- mSPMap.put(1, mSP.load(this, R.raw.buzz4, 1));
- mSPMap.put(2, mSP.load(this, R.raw.alarm1, 1));
- mAudio = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
- private void playSound(int pSound, int pNumber){
- mCurrentVolume = AntiLostDataSource.getAlarmVolume(this);
- if(mCurrentVolume == 0){
- mCurrentVolume = mAudio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
- AntiLostDataSource.setAlarmVolume(this, mCurrentVolume);
- }
- mSP.play(mSPMap.get(pSound), mCurrentVolume, mCurrentVolume, 1, pNumber, 1);
- }
停止:
- private void stopSound(){
- mSP.stop(2);
- }