I'm new to Compose and Android development in general. While building a toy project with Compose, I faced a question. I need to load ~100 short sounds from assets to play them via SoundPool
. SoundPool.load()
loads asynchronously I suppose (otherwise why do we need a callback).
Code in viewmodel:
private val TAG = javaClass.simpleName
private val soundPool: SoundPool
private val soundsInProgress = AtomicInteger(0)
var sounds: List<Sound> by mutableStateOf(listOf())
private set
init {
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
soundPool = SoundPool.Builder()
.setMaxStreams(3)
.setAudioAttributes(audioAttributes)
.build()
loadSoundsFromAssets()
}
private fun loadSoundsFromAssets() {
val assetManager = getApplication<MyApp>().applicationContext.assets
val sounds = assetManager.list("sounds/")!!.map(this::parseSound)
soundsInProgress.set(sounds.size)
soundPool.setOnLoadCompleteListener { _, id, status ->
if (status == 0) {
val left = soundsInProgress.decrementAndGet()
Log.i(TAG, "Loaded 1 sound, $left in progress")
if (left == 0) {
sounds = sounds
}
} else {
Log.e(TAG, "Could not load sound $id, status is $status")
}
}
sounds.forEach {
val soundId = soundPool.load(assetManager.openFd("sounds/" + it.fileName), 0)
it.soundId = soundId
}
}
My aim here is to track progress of sound preloading.
The question is: Is it overkill to use atomic here or is it safe without atomic?
Also, how do I observe changes to soundsInProgress
? MutableState won't work as expected.
from Is there a need to use atomics or other synchronization
No comments:
Post a Comment