Kotlin-添加更多变体-soundPool

时间:2020-09-28 19:55:00

标签: android kotlin audio action soundpool

请帮助。我需要为一个动作添加2种声音,它们会随机变化。我怎么做?我不知道该怎么做。非常感谢。

        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 个答案:

答案 0 :(得分:0)

您可以调用集合中的.random()以获得随机物品。因此,与其将每种声音类型(例如SOUND_HIT)映射到一种声音,不如将每种映射到一个列表声音(如果仅此一项,则可以包含一项)你有)。然后,对于您加载的每种声音,只需将其添加到适当的列表中即可。

这样,当您要播放声音时,可以转到play(sounds[SOUND_SWOOSHING].random()),它将只从该声音类型的列表中选择一个。

您可以按照现在的方式进行设置

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

但是我建议添加一个函数来处理所有加载:

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 ...
)

或者如果您想看中...

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) }
)

不要担心这是否太复杂了,前几个示例很简洁,希望可以很容易理解!我就像您什么时候可以整理所有内容时一样:)