Set the volume of the Android application

In order for the user to be able to manage the volume, my Android application has a menu consisting of a slider that provides int values โ€‹โ€‹from 0 to 10 when dragging and dropping. After I get the value, I have to set the volume to the corresponding value selected by the user, and, well, this is the part that I do not know to implement, and I would like to find about it.

+6
android
source share
1 answer

Use the AudioManager class. Essentially, the code is as follows:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamVolume(streamType, volume, flags); 

The problem is that the volume of the device is not necessarily displayed from 0 to 10, like your slider. On my emulator, it is from 0 to 7. So, you need to getStreamMaxVolume(...) to know what your maximum is, and then work out your value as part of this. For example, if your user selects a volume of 8 out of 10, which is equivalent to 0.8 * 7 = 5.6, which you should round to 6 out of 7.

โ€œstreamโ€ refers to things such as ringer volume, notification volume, music volume, etc. If you want to change the ringer volume, you need to make sure that all your commands have AudioManager.STREAM_RING as streamType.

+11
source share

All Articles