SoundPoolUtil.java
object SoundPoolUtil {
private val soundIds = ConcurrentHashMap()
private val streamIds = ConcurrentHashMap()
private var soundPool: SoundPool? = null
fun initSound(sounds: List?) {
if(soundPool == null) {
val attributes = AudioAttributes.Builder()
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
soundPool = SoundPool.Builder()
.setMaxStreams(5)
.setAudioAttributes(attributes.build())
.build()
}
sounds?.forEach { it ->
val fd = GSBaseApplication.getApplication().assets.openFd(it)
soundIds[it] = soundPool?.load(fd , 1) ?: 0
}
}
fun playSound(url: String , loop: Boolean) {
try{
soundPool?.run {
val soundId = soundIds[url]
soundId?.let {
val streamId = play(it , 1.0f , 1.0f , 0 , if(loop) -1 else 0 , 1.0f)
streamIds[url] = streamId
}
}
}catch (e: Exception){}
}
fun stopSound(url: String) {
try {
streamIds[url]?.let {
soundPool?.stop(it)
}
}catch (e: Exception){}
}
fun pauseSound(url: String?) {
try {
streamIds[url]?.let {
soundPool?.pause(it)
}
}catch (e: Exception){}
}
fun resumeSound(url: String?) {
try {
streamIds[url]?.let {
soundPool?.resume(it)
}
}catch (e: Exception){}
}
fun release() {
try {
soundPool?.release()
soundPool = null
}catch (e: Exception){}
}
}
// 固定线程池
private val workerThread = Executors.newFixedThreadPool(1)
private fun initSoundPools() {
this.workerThread.execute {
SoundPoolUtil.initSound(listOf("audio/eeee.mp3"
, "audio/ee.mp3"
))
}
}



