一、SoundPool相对于MediaPlayer的优点
1.SoundPool适合 短且对反应速度比较高 的情况(游戏音效或按键声等),文件大小一般控制在几十K到几百K,最好不超过1M,
2.SoundPool 可以与MediaPlayer同时播放,SoundPool也可以同时播放多个声音;
3.SoundPool 最终编解码实现与MediaPlayer相同;
4.MediaPlayer只能同时播放一个声音,加载文件有一定的时间,适合文件比较大,响应时间要是那种不是非常高的场景
二、SoundPool API简单说明
SoundPool使用其来播放音乐
1、构造方法
SoundPool (int maxStreams, int streamType, int srcQuality)
//maxStreams 设置soundpool对象的并发流的最大数量
//streamType 设置流的类型,一般为STREAM_MUSIC
//srcQuality 采样转换率的质量 现在没有什么效果 0 设为默认
2、常用方法(加载音频文件)
与MediaPlayer相同 SoundPool 加载音频文件有多种方式
<!--加载应用资源文件--> 注意:切忌使用文件名相同,格式名不同的文件example.mp3 ,example.wav
int load(Context context, int resId, int priority)
<!--从音频文件路径加载-->
int load(String path, int priority)
<!--从asset 文件中加载-->
int load(AssetFileDescriptor afd, int priority)
<!--从文件中加载-->
int load(FileDescriptor fd, long offset, long length, int priority)
stop(int streamID)
pause(int streamID)
resume(int streamID)
release()
<!--设置循环播放 (0 不循环, -1 循环)-->
setLoop(int streamID, int loop)
<!--设置有播放优先级-->
setPriority(int streamID, int priority)
<!--设置播放播放速度 rate值 0.5 ~2.0 之间-->
setRate(int streamID, float rate)
setVolume(int streamID, float leftVolume, float rightVolume)
<!--相对于load方法-->
unload(int soundID)
<!--此方法会遍历所有正在播放的音乐 并设置flag ,在autoResume的时候恢复播放-->
autoPause()
autoResume()
三、SoundPool 简单使用
public class MainActivity extends AppCompatActivity {
HashMap<Integer, Integer> soundMap = new HashMap<>();
SoundPool soundPool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button) ;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
soundPool.play(soundMap.get(0), 1, 1, 1, 0, 1);
}
});
loadAudioResource();
}
private void loadAudioResource(){
soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
if(soundMap.size() > 0){
soundMap.clear();
}
soundMap.put(0, soundPool.load(this, R.raw.warning_lane, 2));
soundMap.put(1, soundPool.load(this, R.raw.warning_car, 3));
soundMap.put(2, soundPool.load(this, R.raw.warning_stopgo, 1));
}
}