使用SoundPool进行游戏

时间:2020-01-13 17:07:21

标签: kotlin soundpool

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已过时 我有点新,所以不知道该如何解决(观看了许多视频并在各处搜索,但我无法修复) 所以也许有人可以帮我告诉我该怎么做

1 个答案:

答案 0 :(得分:0)

不赞成使用的东西时,总应该有一个提示来代替。 因此,您需要使用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中引入了许多与平台相关的问题。