Kotlin - Add more variant - soundPool

Viewed 65

please help. I need to add 2 sounds ogg to one action, which will change randomly. How do I do that? I don't know how to do it. Thank you very much.

        Thread(Runnable {
            val assets = context.resources.assets
            sounds[SOUND_DIE] = soundPool.load(assets.openFd("die.ogg"), 1)
            sounds[SOUND_HIT] = soundPool.load(assets.openFd("hit.ogg"), 1)
            sounds[SOUND_POINT] = soundPool.load(assets.openFd("point.ogg"), 1)
            sounds[SOUND_SWOOSHING] = soundPool.load(assets.openFd("swooshing.ogg"), 1)
            sounds[SOUND_WING] = soundPool.load(assets.openFd("wing.ogg"), 1)
        }).start()
    }
1 Answers

You can call .random() on a collection to get a random item. So instead of mapping each sound type (like SOUND_HIT) to one sound, map each one to a list of sounds (which can contain one item if that's all you have). And then for every sound you load, just add it to the appropriate list.

That way when you want to play a sound, you can go play(sounds[SOUND_SWOOSHING].random()) and it will just pick one from that sound type's list.

You can set it up the way you're doing now

sounds = mapOf(
    SOUND_DIE to listOf(
        soundPool.load(assets.openFd("die.ogg"), 1),
        soundPool.load(assets.openFd("yargh.ogg"), 1)
    ),
    SOUND_HIT to ...
)

but I'd recommend adding a function to handle all that loading:

fun loadSound(filename: String) = soundPool.load(assets.openFd(filename), 1)

sounds = mapOf(
    SOUND_DIE to listOf(
        loadSound("die.ogg"),
        loadSound("yargh.ogg")
    ),
    SOUND_HIT to ...
)

or if you want to get fancy...

val filenamesToTypes = mapOf(
    "die.ogg" to SOUND_DIE,
    "yargh.ogg" to SOUND_DIE,
    "point.ogg" to SOUND_POINT,
   ...
)

// build your sounds collection by grouping all the filenames
// with the same sound type, and transform each filename to a
// loaded sound, so you get a map of SoundType -> List<Sound>
sounds = filenamesToTypes.entries.groupBy(
    keySelector = { it.value },
    valueTransform = { loadSound(it.key) }
)

Don't worry if that feels too complicated, the first couple of examples are neat enough and hopefully easy to follow! I just like when you can organise stuff all snappy :)

Related