coderslay
coderslay

Reputation: 14370

How to check Programmatically the volume of phone in android?

I am developing an application in which i will play music..Now i want to check whether the user has reduced the volume of the phone or not... I want the music to play at a particular volume...How to do it?

Upvotes: 2

Views: 4071

Answers (2)

user16118981
user16118981

Reputation: 209

Expanding on Femi's answer (and with some further cross-referencing against ProgrammerWorld's tutorial on YT), here's how to implement the AudioManager. Here we have a practical example in Kotlin that fetches the current volume and attempts to determine if the device is below a certain quietness threshold (i.e. half of max volume):

class ActivityMain : Activity()  {
    private lateinit var mvAudioManager : AudioManager

    override fun onCreate(mvSavedInstanceState: Bundle?) {
        super.onCreate(mvSavedInstanceState)
        setContentView(R.layout.activity_main) 

        mvAudioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }

    override fun onKeyDown(mvKeyCode: Int, mvEvent: KeyEvent?): Boolean {
        if (mvKeyCode == KeyEvent.KEYCODE_VOLUME_UP || mvKeyCode == KeyEvent.KEYCODE_VOLUME_DOWN || mvKeyCode == KeyEvent.KEYCODE_VOLUME_MUTE)
        {
            val mvVolume = mvAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
            if (mvVolume.toFloat() / mvAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat() <= .5)
                println("Device is quiet... TOO quiet...")
        }
        return super.onKeyDown(mvKeyCode, mvEvent)
    }
}

Upvotes: 0

Femi
Femi

Reputation: 64700

You can use AudioManager.getStreamVolume to fetch the current volume for the media player stream (See STREAM_MUSIC), and AudioManager.setStreamVolume to set it.

Upvotes: 2

Related Questions