【问题标题】:Using SoundPool for games使用 SoundPool 进行游戏
【发布时间】:2020-01-13 17:07:21
【问题描述】:
class SoundPlayer(context: Context) {

// For sound FX
private val soundPool: SoundPool = SoundPool(10, // Here 
    AudioManager.STREAM_MUSIC,
    0)

companion object {
    var playerExplodeID = -1
    var invaderExplodeID = -1
    var shootID = -1
    var damageShelterID = -1
    var uhID = -1
    var ohID = -1
}

init {
    try {
        // Create objects of the 2 required classes
        val assetManager = context.assets
        var descriptor: AssetFileDescriptor


        // Load our fx in memory ready for use
        descriptor = assetManager.openFd("shoot.ogg")
        shootID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("invaderexplode.ogg")
        invaderExplodeID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("damageshelter.ogg")
        damageShelterID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("playerexplode.ogg")
        playerExplodeID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("damageshelter.ogg")
        damageShelterID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("uh.ogg")
        uhID = soundPool.load(descriptor, 0)

        descriptor = assetManager.openFd("oh.ogg")
        ohID = soundPool.load(descriptor, 0)


    } catch (e: IOException) {
        // Print an error message to the console
        Log.e("error", "failed to load sound files")
    }
}

fun playSound(id: Int){
    soundPool.play(id, 1f, 1f, 0, 0, 1f)
}
}

我有一个 SoundPool 无法使用的问题,据说构造函数 SoundPool 已弃用 我有点新,所以不知道如何解决这个问题(观看了很多视频并到处搜索,但我无法解决) 所以也许有人可以帮我告诉我该怎么做

【问题讨论】:

    标签: kotlin soundpool


    【解决方案1】:

    当某些东西被弃用时,总是应该提示使用什么来代替。 所以你需要使用SoundPool.Builder 来创建一个对象的新实例。 但是如果你的目标是在SoundPool.Builder 之前发布的 API 级别,那么你会得到ClassNotFoundException。 所以一般的做法是在API X之前(引入新功能时)检查API级别并以旧方式做事,以及API X之后的新方式:

    @Suppress("DEPRECATION")
    fun buildSoundPool(maxStreams: Int):SoundPool =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val attrs = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_GAME)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build()
            SoundPool.Builder()
                .setAudioAttributes(attrs)
                .setMaxStreams(maxStreams)
                .build()
        } else {
            SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0)
        }
    

    然后:

    private val soundPool: SoundPool = buildSoundPool(10)
    

    我还建议使用my custom implementation of SoundPool,因为在 Android 上不同版本的原始 SoundPool 中引入了许多平台相关问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多