《Android编程权威指南》第 20 章,本章将会学习到单元测试,所谓单元测试就是编写小程序去验证主应用各个单元的独立行为,即测试一个个的类。
一、创建 SoundPool
SoundPool.Builder 可以创建一个 SoundPool 实例。setMaxStreams(Int) 可以指定某个时刻同时播放多少个音频
BeatBox.kt:
...
private const val MAX_SOUNDS = 5
class BeatBox(private val assets: AssetManager) {
...
private val soundPool = SoundPool.Builder().setMaxStreams(MAX_SOUNDS).build()
...
}
已经播放了五个音频时,如果再尝试播放第6个,SoundPool 则会停止播放最早播放的那个音频。还可以使用 setAudioAttributes(AudioAttributes) 指定其他不同音频流属性。
有关 SoundPool 类的文档请参考:
developer.android.com/reference/a…
二、访问 Assets
需要使用 AssetManager 对象去访问并播放音频文件。
val assetPath = sound.assetPath
val assetManger = context.assets
val soundData = assetManger.open(assetPath)
对于有的 API(比如 SoundPool )需要 FileDescriptor。那么可以转而调用 AssetManager.openFd(String)
三、加载音频文件
使用 SoundPool 加载音频文件,可快速相应,不过它也需要预先加载音频。
先给 Sound 类中添加 soundId 属性,它是个可空类型,在它没有值得时候,可以设置为 null。
class Sound(val assetPath: String, var soundId: Int? = null) {
val name = assetPath.split("/").last().removeSuffix(WAV)
}
在 BeatBox 中添加 load(Sound) 函数载入音频。
private fun load(sound: Sound) {
val afd: AssetFileDescriptor = assets.openFd(sound.assetPath)