一個遊戲的背景音樂僅僅需要在遊戲運行的時候播放,而在返回到桌面或者進入其他應用使遊戲的activity變為不可見時,都應該立即停止播放,所以遊戲的背景音效或音樂播放根本沒必要使用service。
有人可能說播放背景音樂應該在後台執行,不能影響程序的正常運行,這樣說當然正確,但這僅需要開一個單獨的執行緒來專門播放音樂就可以了,而經我測試,MediaPlayer和SoundPool本身都已經實現了在獨立的執行緒中播放音樂,所以綜上所述在遊戲中播放背景音樂完全沒必要使用 service,那樣完全是捨近求遠,畫蛇添足之舉。只需直接使用MediaPlayer即可。
以下是一個實現遊戲中播放聲音的類別,封裝了MediaPlayer和SoundPool的使用細節,所有方法都定義為靜態方法,在程序啟動時先調用其init方法,然後在任何地方都可以非常方便的使用
public class Sound {
private static MediaPlayer music;
private static SoundPool soundPool;
private static boolean musicSt = true; //音樂開關
private static boolean soundSt = true; //音效開關
private static Context context;
private static final int[] musicId = {R.raw.bg};
private static Map<Integer,Integer> soundMap; //音效資源id與加載過後的音源id的映射關係表
/**
* 初始化方法
* @param c
*/
public Sound(Context c)
{
context = c;
initMusic();
initSound();
}
//初始化音效播放器
private static void initSound()
{
soundPool = new SoundPool(10,AudioManager.STREAM_MUSIC,100);
soundMap = new HashMap<Integer,Integer>();
soundMap.put(R.raw.right, soundPool.load(context, R.raw.right, 1));
soundMap.put(R.raw.wrong, soundPool.load(context, R.raw.wrong, 1));
}
//初始化音樂播放器
private static void initMusic()
{
int r = new Random().nextInt(musicId.length);
music = MediaPlayer.create(context,musicId[r]);
music.setLooping(true);
}
/**
* 播放音效
* @param resId 音效資源id
*/
public static void playSound(int resId)
{
if(soundSt == false)
return;
Integer soundId = soundMap.get(resId);
if(soundId != null)
soundPool.play(soundId, 1, 1, 1, 0, 1);
}
/**
* 切換一首音樂並播放
*/
public static void changeAndPlayMusic()
{
if(music != null)
music.release();
initMusic();
setMusicSt(true);
}
/**
* 獲得音樂開關狀態
* @return
*/
public static boolean isMusicSt() {
return musicSt;
}
/**
* 設置音樂開關
* @param musicSt
*/
public static void setMusicSt(boolean musicSt) {
Sound.musicSt = musicSt;
if(musicSt)
music.start();
else
music.stop();
}
/**
* 獲得音效開關狀態
* @return
*/
public static boolean isSoundSt() {
return soundSt;
}
/**
* 設置音效開關
* @param soundSt
*/
public static void setSoundSt(boolean soundSt) {
Sound.soundSt = soundSt;
}
/**
* 釋放資源
*/
public void recyle()
{
music.release();
soundPool.release();
soundMap.clear();
}
}
只要在想使用音效資源的地方使用 Sound sound = new Sound(BaseActivity.context); Sound.playSound(R.raw.wrong); Sound.setMusicSt(false); sound.recyle();用完記得要釋放資源!!

沒有留言 :
張貼留言