(1)代码:
public class SmallSound {
private SoundPool mSp;
private HashMap map;
private Context mContext;
private float mAudioRatio;
//构造方法
public SmallSound(Context context) {
mContext = context;
initSoundpool();
}
//采用hashmap存储键值对的方式存储音效
private void initSoundpool() {
//参数1:同时播放音效数量 2.常量 3.音乐品质
mSp = new SoundPool(100, AudioManager.STREAM_MUSIC, 5);
map = new HashMap<>();
AudioManager am = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE);
float audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
//获得声音比率
mAudioRatio = audioCurrentVolume / audioMaxVolume;
}
/**
* 加载资源
* @param id
* @param raw
*/
public void loadRes(int id, int raw) {
//后一个id是指优先级
map.put(id, mSp.load(mContext, raw, id));
}
/**
* 对外提供方法,用于音乐播放
* @param id
* @param repeatCount
*/
public void playSound(final int id, final int repeatCount) {
//参数1:资源 参数2: 左声道 参数3:右声道 参数4:优先级 参数5:循环次数(0不循环,-1无限循环) 参数6:回放速度(0.5到2,1是正常)
mSp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
soundPool.play(map.get(id), mAudioRatio, mAudioRatio, id, repeatCount, 1);
}
});
}
(2)使用:
SmallSound mSoundActivity = new SmallSound(this);
mSoundActivity.loadRes(id,raw);
mSoundActivity.playSound(id,0(循环次数));
(3)声明:
raw指的是raw下的资源文件
}