kotlin 如何正确调整在Android Studio中按下按钮时的声音?

wbgh16ku  于 2023-11-21  发布在  Kotlin
关注(0)|答案(2)|浏览(143)

我正在尝试做一个游戏,你必须记住点击4个按钮的顺序。如果我按下按钮几次,按下的声音消失。
我试着在点击它们时调整声音,点击声音需要1秒钟。告诉我我在哪里犯了错误,以及如何做对。

class MainActivity : AppCompatActivity() {
    private lateinit var mainView: ActivityMainBinding

    private lateinit var sound: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainView = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainView.root)

        mainView.apply {

            blueButton.setOnClickListener {
                sound = MediaPlayer.create(applicationContext, R.raw.blue_bt_tap_sound)
                play(sound)
            }

            redButton.setOnClickListener {
                sound = MediaPlayer.create(applicationContext, R.raw.red_bt_tap_sound)
                play(sound)
            }

            greenButton.setOnClickListener {
                sound = MediaPlayer.create(applicationContext, R.raw.green_bt_tap_sound)
                play(sound)
            }

            yellowButton.setOnClickListener {
                sound = MediaPlayer.create(applicationContext, R.raw.yellow_bt_tap_sound)
                play(sound)
            }

        }
    }

    private fun play(buttonSound: MediaPlayer) {
        buttonSound.start()
    }

}

字符串

yxyvkwin

yxyvkwin1#

在播放另一个声音之前,你必须停止并释放MediaPlayer。有关Kotlin中所需的命令,请参阅here,但请先阅读所有其他答案。它们是用Java编写的,但你仍然应该理解它们。

7dl7o3gd

7dl7o3gd2#

尝试添加方法stop()

private fun stop() {
    sound?.stop()
    sound?.release()
    sound = null
}

字符串
然后停止播放器,如果它不是空的,然后再创建一个新的:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainView = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainView.root)

        mainView.apply {

            blueButton.setOnClickListener {
                stop()
                sound = MediaPlayer.create(applicationContext, R.raw.blue_bt_tap_sound)
                play(sound)
            }

            redButton.setOnClickListener {
                stop()
                sound = MediaPlayer.create(applicationContext, R.raw.red_bt_tap_sound)
                play(sound)
            }

            greenButton.setOnClickListener {
                stop()
                sound = MediaPlayer.create(applicationContext, R.raw.green_bt_tap_sound)
                play(sound)
            }

            yellowButton.setOnClickListener {
                stop()
                sound = MediaPlayer.create(applicationContext, R.raw.yellow_bt_tap_sound)
                play(sound)
            }

        }
    }

相关问题