Android : How to set MediaPlayer volume programmatically?

后端 未结 10 522
你的背包
你的背包 2020-12-08 04:17

How to set the mediaplayer volume programmatically. I use it for alarm notification. Any help is highly appreciated and thanks in advance.

10条回答
  •  Happy的楠姐
    2020-12-08 04:39

    You can do the below using Kotlin, this code will check if the media volume is more than 20% of the maximum volume of the device, and will reduce it to be 20% only.

        val audio = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
    
        val maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val percent = 0.2f
        val twintyVolume = (maxVolume * percent).toInt()
    
        if ( level > twintyVolume) {
            Toast.makeText(this,"audio level is $level", Toast.LENGTH_LONG).show()
            audio.setStreamVolume(AudioManager.STREAM_MUSIC,twintyVolume,0)
        }
    

提交回复
热议问题