Android SoundPool

来源:互联网 发布:网站备案域名怎么买 编辑:程序博客网 时间:2024/06/05 14:46




 SoundPool


SoundPool 主要用于播放一些较短的声音片段,与 MediaPlayer 相比, 
SoundPool 的优势在于 CPU 资源占用量低和反应延迟小。另外, 
SoundPool 还支持自行设置声音的品质、音量、 播放比率等参数。


SoundPool(int maxStreams, int streamType, int srcQuality) 
:第一个参数指定支持多少个声音;第二个参数指定声音类型:第三个参数指定声音品质。


使用 SoundPool 播放声音的步骤如下:


1)调用 SoundPool 的构造器创建 SoundPool 的对象。


2)调用 SoundPool 对象的 load() 方法从指定资源、文件中加载声音。最好使用 HashMap< Integer, Integer> 来管理所加载的声音。


3)调用 SoundPool 的 play 方法播放声音。






1.初始化对象
SoundPool soundPool;
HashMap<Integer, Integer> musicId = new HashMap<Integer, Integer>();


2.创建SoundPool对象添加声音文件
// 初始化 soundPool, 设置可容纳 12 个音频流,音频流的质量为 5 ,
soundPool = new SoundPool(12, 0, 5);
// 通过 load 方法加载指定音频流,并将返回的音频 ID 放入 musicId 中
musicId.put(1, soundPool.load(this, R.raw.if1, 1));
musicId.put(2, soundPool.load(this, R.raw.if2, 1));
musicId.put(3, soundPool.load(this, R.raw.if3, 1));

3.调用播放
/**
* SoundPool 提供的播放指定声音的方法:

* int play(int soundID, float leftVolume, float rightVolume, int
* priority, int loop, float rate) :该方法的第一个参数指定播放哪个声音; leftVolume 、
* rightVolume 指定左、右的音量: priority 指定播放声音的优先级,数值越大,优先级越高; loop
* 指定是否循环, 0 为不循环, -1 为循环; rate 指定播放的比率,数值可从 0.5 到 2 , 1 为正常比率。
*/
soundPool.play(musicId.get(1), 1, 1, 0, 0, 1);


注意 soundPool.play() 返回一个当前播放音乐的 int soundID 这个Id用于停止使用
如果 soundPool.stop(soundID);  soundPool.pause(soundID);










0 0
原创粉丝点击