开发中有碰到需要加载本地音频资源的功能模块,具体的可以看下述实现代码;
实现类:
public class SoundPoolUtils {
private static SoundPool soundPool;
// SoundPool对象
public static SoundPool mSoundPlayer = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
public static SoundPoolUtils soundPlayUtils;
// 上下文
static Context mContext;
/**
* 初始化
*
* @param context
*/
public static SoundPoolUtils init(Context context) {
if (soundPlayUtils == null) {
soundPlayUtils = new SoundPoolUtils();
}
// 初始化声音
mContext = context;
mSoundPlayer.load(mContext, R.raw.exception, 1);// 1
mSoundPlayer.load(mContext, R.raw.left_break, 1);// 2
mSoundPlayer.load(mContext, R.raw.left_front, 1);// 3
mSoundPlayer.load(mContext, R.raw.right_break, 1);// 4
mSoundPlayer.load(mContext, R.raw.right_front, 1);// 5
mSoundPlayer.load(mContext, R.raw.exceptions, 1);// 5
return soundPlayUtils;
}
/**
* 播放声音
*
* @param soundID
*/
public static void play(final int soundID) {
mSoundPlayer.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mSoundPlayer.play(soundID, 1, 1, 10, 0, 1); //防止系统内存不够导致的无声问题
}
});
}
}
调用方式如下:
1:初始化资源文件:
SoundPoolUtils .init(context);
2:调用函数播放音频
SoundPoolUtils .play(1); 或者play(2)...依此类推
备注:播放视频的时候,一定是需要做个延时,或者在onClick里面实现,因为初始化资源是需要花一定时间的