Wednesday, April 18, 2018

android kotlin - Set media volume programmatically

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.media.AudioManager
import android.widget.Toast
import java.util.*


class MainActivity : AppCompatActivity() {

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

        // Get the audio manager system service
        val audioManager: AudioManager = getSystemService(AUDIO_SERVICE) as AudioManager

        // Click listener for button widget
        button.setOnClickListener {
            // Get the maximum media/music volume
            val maxVolume = audioManager.mediaMaxVolume

            // Get a random volume index in a range
            val randomIndex = Random().nextInt(((maxVolume - 0) + 1) + 0)

            // Set the media/music volume programmatically
            //audioManager.setMediaVolume(maxVolume)
            audioManager.setMediaVolume(randomIndex)

            // Show volume index in a toast message
            toast("Max: $maxVolume / Current: ${audioManager.mediaCurrentVolume}")
        }
    }
}


// Extension function to change media volume programmatically
fun AudioManager.setMediaVolume(volumeIndex:Int) {
    // Set media volume level
    this.setStreamVolume(
            AudioManager.STREAM_MUSIC, // Stream type
            volumeIndex, // Volume index
            AudioManager.FLAG_SHOW_UI// Flags
    )
}


// Extension property to get media maximum volume index
val AudioManager.mediaMaxVolume:Int
get() = this.getStreamMaxVolume(AudioManager.STREAM_MUSIC)


// Extension property to get media/music current volume index
val AudioManager.mediaCurrentVolume:Int
get() = this.getStreamVolume(AudioManager.STREAM_MUSIC)


// Extension function to show toast message
fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_layout"
    android:background="#786861"
    android:padding="16dp"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Media Volume"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        />
</LinearLayout>