Skip to content

Adjust Volume

Retrieve the AudioManager for later use

val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
// Define which stream you want to control (usually STREAM_MUSIC for media)
val streamType = AudioManager.STREAM_MUSIC
// Get the max volume to calculate a percentage
val maxVolume = audioManager.getStreamMaxVolume(streamType)
// Calculate 50% volume
val targetVolume = maxVolume / 2
// Set the volume
audioManager.setStreamVolume(
streamType,
targetVolume,
AudioManager.FLAG_SHOW_UI // This flag shows the system volume slider overlay
)

or you can set the volume by built-in step

// Increase volume by one step
audioManager.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE,
AudioManager.FLAG_SHOW_UI
)
// Decrease volume by one step
audioManager.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER,
AudioManager.FLAG_SHOW_UI
)