既然音频资源文件已准备就绪,现在就来学习如何播放这些.wav音频文件。Android的大部分音频API都比较低级,掌握它们不是那么容易。不过没关系,针对BeatBox应用,可以使用SoundPool这个特别定制的实用工具。 SoundPool能加载一批声音资源到内存中,并支持同时播放多个音频文件。
1. 创建 SoundPool
在 Lollipop 中引入了新的方式创建SoundPool:使用SoundPool.Builder。不过,为了兼容API 16 最低级别,只能选择使用SoundPool(int, int, int)这个老构造方法了。一个代码示例如下:
if (Build.VERSION.SDK_INT >= 21) {
mSoundPool = new SoundPool.Builder()
.setMaxStreams(MAX_SOUNDS)
.setAudioAttributes(new AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.build())
.build();
} else {
// This old constructor is deprecated, but we need it for