这两天开发适配7.0遇见一个坑. 7.0手机在游戏开局两局后 声音会 播放不出来. 需要适配7.0的声音. 不多说,亮代码
一开始 我用MediaPlayer播放声音.
GameMediaPlayer.StarPlay(GameDrawStart.this, 3);GameMediaPlayer中的方法是:
public class GameMediaPlayer { public static void StarPlay(Context context, int Type) { MediaPlayer mMediaPlayer = null; switch (Type) { //死亡 case 1: mMediaPlayer = MediaPlayer.create(context, R.raw.dead); mMediaPlayer.start(); break; //游戏输了 case 2: mMediaPlayer = MediaPlayer.create(context, R.raw.gamelow); mMediaPlayer.start(); break; default: break; } } }但是,用MediaPlayer,会造成在部分7.0手机上,游戏开局几局后,声音播放不出来.
后来,换成了播放声音的另一种方式SoundPool.
使用SoundPool时,刚开始也遇见了一个坑,声音会失真.
下面亮出声音失真的代码:
SoundPool.
我在对应调用声音的地方,
play(5, 0);
private Map<Integer, Integer> mapSRC; private SoundPool sp; //声音池 //初始化声音池 private void initSoundPool(){ sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); mapSRC = new HashMap<Integer, Integer>(); mapSRC.put(1, sp.load(this, R.raw.gamedrawansererro, 0)); mapSRC.put(2, sp.load(this, R.raw.gamedrawanserright, 0)); mapSRC.put(3, sp.load(this, R.raw.timecoundown, 0)); mapSRC.put(4, sp.load(this, R.raw.gamelow, 0)); mapSRC.put(5, sp.load(this, R.raw.gamewinner, 0)); } private void play(int sound, int number){ sp.play(mapSRC.get(sound),//播放的声音资源 1.0f,//左声道,范围为0--1.0 1.0f,//右声道,范围为0--1.0 0, //优先级,0为最低优先级 number,//循环次数,0为不循环 0);//播放速率,0为正常速率 }结果还会失真.
后来换成
private SoundPool soundPool;
soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5); soundMap.put(1, soundPool.load(this, R.raw.gamedrawansererro, 1)); soundMap.put(2, soundPool.load(this, R.raw.gamedrawanserright, 1)); soundMap.put(3, soundPool.load(this, R.raw.timecoundown, 1)); soundMap.put(4, soundPool.load(this, R.raw.gamelow, 1)); soundMap.put(5, soundPool.load(this, R.raw.gamewinner, 1));
注意 在当前activity销毁时 要注销SoundPool
@Override protected void onDestroy() { super.onDestroy(); if(soundPool != null){ soundPool.release(); } }