顾名思义游戏音效就是用户在玩游戏时出现的伴随音乐,是每个游戏开发必须的一部分,但如果你做的游戏背景音乐有间断的话,可以用getCurrentPosition()这个方法来判断一下声音播放的偏移。这个其实是很简单的,只要我们在代码当中设置好初始化声音和加载音效资源就可以了,其他的就和音乐播放器的代码差不多,比如开始、停止。话不多说了,我们还是来看看是如何用代码当来实现音效的吧:
//音效的音量
intstreamVolume;
//定义SoundPool对象
privateSoundPoolsoundPool; //定义HASH表
privateHashMapsoundPoolMap;
/***************************************************************
*Function:initSounds();
*Parameters:null
*Returns:None.
*Description:初始化声音系统
*Notes:none.
***************************************************************/
publicvoidinitSounds(){
//初始化soundPool对象,第一个参数是允许声音流同时播放的数量,第2个参数是声音类型,第三个参数是声音的品质
soundPool=newSoundPool(100,AudioManager.STREAM_MUSIC,100);
//初始化Hash表
soundPoolMap=newHashMap();
//获得声音设备和设备音量
AudioManagermgr=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
streamVolume=mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
}
/***************************************************************
*Function:loadSfx();
*Parameters:null
*Returns:None.
*Description:加载音效资源
*Notes:none.
***************************************************************/
publicvoidloadSfx(intraw,intID){
//把资源中的音效加载到指定的ID(播放的时候就对应到这个ID进行播放)
soundPoolMap.put(ID,soundPool.load(context,raw,ID));
}
/***************************************************************
*Function:play();
*Parameters:sound:要播放的音效的ID,loop:循环次数
*Returns:None.
*Description:播放声音
*Notes:none.
***************************************************************/
publicvoidplay(intsound,intuLoop){
soundPool.play(soundPoolMap.get(sound),streamVolume,streamVolume,1,uLoop,1f);
}