android----使用SoundPool播放声音
2016-12-16 10:42
555 查看
SoundPool适合短频播放
初始化
初始化SoundPool 我们直接new SoundPool (int maxStreams, int streamType, int srcQuality)即可
参数解释:
加载音频
播放音频
SoundPool API大于21之后使用SoundPool.Builder
private SoundPool mSoundPool; private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>(); private void initSP() throws Exception { //当前系统的SDK版本大于等于21(Android 5.0)时 if (Build.VERSION.SDK_INT >= 21) { SoundPool.Builder builder = new SoundPool.Builder(); //传入音频数量 builder.setMaxStreams(2); //AudioAttributes是一个封装音频各种属性的方法 AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder(); //设置音频流的合适的属性 attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC); //加载一个AudioAttributes builder.setAudioAttributes(attrBuilder.build()); mSoundPool = builder.build(); } //当系统的SDK版本小于21时 else {//设置最多可容纳2个音频流,音频的品质为5 mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5); } soundID.put(1, mSoundPool.load(this, R.raw.clearning, 1)); // try{ // Thread.sleep(1000);//如果报错误sample 1 not ready 一般都是因为资源文件没有加载完.所以要设置一个睡眠时间等待加载 // } // catch (Exception e){} }
封装
/** * 封装 */ public class SoundPlayUtils { public static SoundPool mSoundPool; public static SoundPlayUtils soundPlayUtils; public static Context mCotext; public static SoundPlayUtils init(Context context){ if (soundPlayUtils==null){ soundPlayUtils=new SoundPlayUtils(); } mCotext=context; //当前系统的SDK版本大于等于21(Android 5.0)时 if (Build.VERSION.SDK_INT >= 21) { SoundPool.Builder builder = new SoundPool.Builder(); //传入音频数量 builder.setMaxStreams(2); //AudioAttributes是一个封装音频各种属性的方法 AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder(); //设置音频流的合适的属性 attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC); //加载一个AudioAttributes builder.setAudioAttributes(attrBuilder.build()); mSoundPool = builder.build(); } //当系统的SDK版本小于21时 else {//设置最多可容纳2个音频流,音频的品质为5 mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5); } mSoundPool.load(context, R.raw.clearning, 1);//加载资源 return soundPlayUtils; } /* 播放,你想要播放第几个就传入几 */ public static void play(int pid){ mSoundPool.play(pid, 1, 1, 0, 0, 1); } }
相关文章推荐
- 一步步实现一个简单的下拉刷新上拉加载的通用框架
- 整理----通过/proc/diskstat 计算android I/O数据
- SEAndroid安全机制中的进程安全上下文的关联分析
- android打开office资源
- Android自定义加载动画
- android MediaCodec 音频编解码的实现——转码(好文)
- android 开发 ANR
- Android状态栏微技巧
- Android 判断是开发debug模式,还是发布release模式的方法
- Android onTouchEvent java.lang.IndexOutOfBoundsException
- Android rxjava内存泄漏问题
- Android 定时器的三种实现方法
- Android adb logcat 命令查看日志详细介绍
- 在android4.4上新增加keycode
- 修改Android开机动画
- Android中的动画
- SEAndroid安全机制中的文件安全上下文的关联分析
- Android中使用MediaCodec硬件解码,高效率得到YUV格式帧
- menu用法简介
- Android Things简介