在android中,可以使用SoundPool来实现游戏音效。使用SoundPool的优点是异步线程,占用资源少,可以同时合成多种音效,因而比较适合于在游戏中使用,比如打斗声,效果声,按钮声等。
用SoundPool载入和播放多个音效时,建议使用相同参数的声音文件(如位速,声道,采样率等),并且最好使用OGG格式,否则某些型号的手机可能会出现杂音,重复播放等问题。
int streamVolume;
private SoundPool soundPool;
private HashMap<Integer, Integer> soundPoolMap;
Context ctx;
public void initSounds(Context context)
{
ctx = context;
//初始化soundPool 对象,第一个参数是允许有多少个声音流同时播放,第2个参数是声音类型,第三个参数是声音的品质
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
//初始化HASH表
soundPoolMap = new HashMap<Integer, Integer>();
//获得声音设备和设备音量
AudioManager mgr = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
}
public void loadSfx(int raw, int ID)
{
//raw为声音资源名,ID为自己分配的识别号,播放时用此ID即可
soundPoolMap.put(ID, soundPool.load(ctx, raw, ID));
}
public void play(int ID, int uLoop)
{
soundPool.play(soundPoolMap.get(ID), streamVolume, streamVolume, 0, uLoop, 1f);
}
public void replease()
{
soundPool.release();
}