Android:SoundPool——音乐播放器

一、SoundPool和MediaPlayer的异同

MediaPlayer的缺点:

  1. 如果应用程序需要播放密集,短促的音效,这时用MediaPlayer就不合适。
  2. MediaPlayer资源占用高,延迟时间较长,不支持多个音频同事播放。

SoundPool的优点:

  • SoundPool适合 短且对反应速度比较高 的情况(游戏音效或按键声等),文件大小一般控制在几十K到几百K,最好不超过1M。
  • SoundPool占用CPU低,延迟小,支持自行设置声音品质,音量,播放比率。
  • SoundPool 可以与MediaPlayer同时播放,SoundPool也可以同时播放多个声音。
  • SoundPool 最终编解码实现与MediaPlayer相同。
  • MediaPlayer只能同时播放一个声音,加载文件有一定的时间,适合文件比较大,响应时间要是那种不是非常高的场景。

二,SoundPool的使用

一,SoundPool的创建

private SoundPool soundPool;
AudioAttributes attr = new AudioAttributes.Builder().setUsage(
                AudioAttributes.USAGE_GAME) // 设置音效使用场景 //用于游戏音频时使用的使用值。
                // 设置音效的类型 //当内容类型为音乐时要使用的内容类型值。
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();

soundPool = new SoundPool.Builder().setAudioAttributes(attr) // 设置音效池的属性
                .setMaxStreams(10) // 设置最多可容纳10个音频流
                .build();

二,SoundPool加载音效

int soundID=soundPool.load(this, R.raw.bomb, 1)
====================================
//可以通过四种途径来记载一个音频资源:
//1.通过一个AssetFileDescriptor对象
//int load(AssetFileDescriptor afd, int priority)
//2.通过一个资源ID
//int load(Context context, int resId, int priority)
//3.通过指定的路径加载
//int load(String path, int priority)
//4.通过FileDescriptor加载
//int load(FileDescriptor fd, long offset, long length, int priority)
//声音ID 加载音频资源,这里用的是第二种,第三个参数为priority,声音的优先级*API中指出,priority参数目前没有效果,建议设置为1。
//上下文,声音ID 加载音频资源,第三个参数为priority,声音的优先级*API中指出,priority参数目前没有效果,建议设置为1。

三,SoundPool播放音乐

 int streamID = soundPool.play(soundID, 1f, 1f, 0, 1, 1f);
=====================================
//第一个参数soundID
//第二个参数leftVolume为左侧音量值(范围= 0.0到1.0)
//第三个参数rightVolume为右的音量值(范围= 0.0到1.0)
//第四个参数priority 为流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
//第五个参数loop 为音频重复播放次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次
//第六个参数 rate为播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)

四,SoundPool播放控制

soundPool.pause(mStreamID);
soundPool.resume(mStreamID);
soundPool.stop(mStreamID);
===============================
//pause方法用来暂停指定mStreamID的流 (暂停播放)
//resume方法用来恢复指定mStreamID的流 (恢复播放)
//stop方法用来停止指定mStreamID的流 (停止播放)

五,SoundPool音量调节

soundPool.setVolume(mStreamID, leftVolume, rightVolume);
//leftVolume:左声道音量
发布了360 篇原创文章 · 获赞 163 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/105072442