The Wayback Machine - https://web.archive.org/web/20240913050206/https://www.geeksforgeeks.org/increase-or-decrease-the-volume-programmatically-in-android-using-jetpack-compose/
Open In App

Increase or Decrease the Volume Programmatically in Android using Jetpack Compose

Last Updated : 26 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Many times while building an android application such as using an audio player like a music player. We have to add functionality to add a volume controller for our media player within our application. So that we can control the volume of our media player. In this article, we will take a look at How to adjust the volume of an android phone programmatically in android using Jetpack Compose. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color to the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.newcanaryproject
 
import android.content.Context
import android.content.Context.AUDIO_SERVICE
import android.media.AudioManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
import com.github.skydoves.colorpicker.compose.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
 
                    // on the below line we are specifying
                    // the theme as the scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying the top bar.
                        topBar = {
 
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying
                                // title for our top bar.
                                title = {
 
                                    // in the top bar we are specifying tile as a text
                                    Text(
 
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling color picker method
                        volumeController(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
@Composable
fun volumeController(context: Context) {
 
    // Declare an audio manager
    val audioManager = context.getSystemService(AUDIO_SERVICE) as AudioManager
     
    // on below line we are creating variables for
    // volume level, max volume, volume percent.
    val volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
    val maxVolumeLevel = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    val volumePercent = (volumeLevel.toFloat() / maxVolumeLevel * 100).toInt()
     
    // on below line we are creating a variable
    // for current volume and initializing it.
    val currentVolume = remember {
        mutableStateOf(volumePercent)
    }
 
    // on below line we are creating a column,
    Column(
        // on below line we are adding a modifier to it,
        modifier = Modifier
            .fillMaxSize()
            // on below line we are adding a padding.
            .padding(all = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
 
        // on below line we are displaying a
        // text as volume controller.
        Text(
            text = "Volume Controller",
            // on below line we are adding font weight
            fontWeight = FontWeight.Bold,
             
            // on below line we are adding font size.
            fontSize = 20.sp,
             
             // on below line we are adding text color.
            color = greenColor,
        )
 
        // on below line we are creating text to display volume level.
        Text(
            text = "Volume Level : " + currentVolume.value,
            // on below line we are adding font weight.
            fontWeight = FontWeight.Bold,
            // on below line we are adding font size and color.
            fontSize = 20.sp,
            color = greenColor
        )
 
        // on below line we are creating a row for buttons.
        Row(modifier = Modifier.padding(4.dp)) {
 
            // below line is use to create a button.
            Button(
                // below line is use to add onclick
                // parameter for our button onclick
                onClick = {
                    // on below line we are increasing our volume.
                    audioManager.adjustVolume(
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND
                    )
                    // on below line we are getting our current volume level.
                    val volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                    val maxVolumeLevel = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
                    val volumePercent = (volumeLevel.toFloat() / maxVolumeLevel * 100).toInt()
                    currentVolume.value = volumePercent
                },
                // in below line we are using modifier
                // which is use to add padding to our button
                modifier = Modifier.padding(all = Dp(10F)),
 
                // below line is use to set or
                // button as enable or disable.
                enabled = true,
 
                // below line is use to
                // add border to our button.
                border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue)),
 
                // below line is use to add shape for our button.
                shape = MaterialTheme.shapes.medium,
                // on below line we are updating color for our button.
                colors = ButtonDefaults.buttonColors(backgroundColor = greenColor),
            ) {
                // on below line we are adding text for our button.
                Text(text = "+")
            }
 
            // on below line we are adding a spacer.
            Spacer(modifier = Modifier.width(20.dp))
 
            // below line is use to create a button.
            Button(
                // below line is use to add onclick
                // parameter for our button onclick
                onClick = {
                    // on below line we are decreasing volume
                    audioManager.adjustVolume(
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND
                    )
                    // on below line we are getting our current volume level.
                    val volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                    val maxVolumeLevel = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
                    val volumePercent = (volumeLevel.toFloat() / maxVolumeLevel * 100).toInt()
                    currentVolume.value = volumePercent
                },
 
                // on below line we are updating color for our button.
                colors = ButtonDefaults.buttonColors(backgroundColor = greenColor),
 
                // in below line we are using modifier
                // which is use to add padding to our button
                modifier = Modifier.padding(all = Dp(10F)),
 
                // below line is use to set or
                // button as enable or disable.
                enabled = true,
 
                // below line is use to
                // add border to our button.
                border = BorderStroke(width = 1.dp, brush = SolidColor(Color.Blue)),
 
                // below line is use to add shape for our button.
                shape = MaterialTheme.shapes.medium,
            ) {
                // on below line we are creating a text.
                Text(text = "-")
            }
        }
    }
}


Now run your application to see the output of the application. 

Output:



Similar Reads

How to Increase/Decrease Screen Brightness using Volume Keys Programmatically in Android?
Screen brightness is one such factor that directly affects the Users as well as the Battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is present, set on or off, or absent in any device, a
5 min read
Increase or Decrease Brightness in Android using Jetpack Compose
Screen brightness is adjusted in many android applications while interacting with the screens. In the application, if we are displaying a QR code in that case we have to increase the screen brightness so that the QR code will be properly visible to the scanner. In this article, we will take a look at How to programmatically increase/decrease the br
5 min read
How to Increase or Decrease TextView Font Size in Android Programmatically?
In this App, we are going to learn how to increase or decrease TextView Font Size in Android programmatically. Like we have seen that in many apps we sometimes want to enlarge the text. So here basically we are going to implement that. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going t
3 min read
How to Increase/Decrease Screen Brightness in Steps Programmatically in Android?
Screen brightness is one such factor that directly affects the Users as well as the Battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is present, set on or off, or absent in any device, a
5 min read
How to Get the Device's IMEI/ESN Programmatically in Android using Jetpack Compose?
Android applications many times require the unique identity of the user while developing applications. This unique identity is used to identify the user of the application. Many android apps use the IMEI number as the unique identity of each user. In this article, we will take a look at How to get Device IMEI and ESN Programmatically in android usi
4 min read
How to Check if the Battery is Charging or not in Android Programmatically using Jetpack Compose?
Many times while building an android application we have to check the charging status of the battery whether the battery is currently charging or not. For checking the battery charging status within the android application. We use battery manager. In this article, we will take a look at How to use Battery Manager to check battery charging status wi
5 min read
Android Jetpack Compose - Change the Screen Orientation Programmatically using a Button
Many times in android applications we have to programmatically change the screen orientation to perform some task. If we want to play a video in landscape mode then we have to switch to landscape mode within our android application. So we have to change screen orientation in our android application programmatically. In this article, we will take a
4 min read
Android Jetpack Compose - Interoperability Using Compose in XML Layouts
Writing UI in jetpack compose can be fun, but can be difficult to migrate your whole project into Compose at one time. Fortunately, Jetpack Compose provides Interoperability api to use compose in existing XML views so that you can migrate to compose slowly. Prerequisites: Knowledge of Jetpack Compose.Knowledge of KotlinKnowledge of Android’s View.
3 min read
How to Increase/Decrease Fading Rate of FadingTextView in Android?
Prerequisite: How to add fading TextView animation in Android TextView is the basic building block of user interface components. It is used to set the text and display it to the user. It is a very basic component and used a lot. A Fading TextView is a TextView that changes its content automatically every few seconds. So the question is now why to i
4 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
How to Adjust the Volume of Android Phone Programmatically from the App?
As stated in the title of this article let's discuss how to adjust the volume of an Android Phone programmatically from the App. Basically, control the volume in the app mean Increase or Decrease the Volume without the Volume Bar UIIncrease or Decrease the Volume with the Volume Bar UIMute or Unmute the device So we are going to discuss all these t
5 min read
How to Listen for Volume Button and Back Key Events Programmatically in Android?
By production, Android devices are provided with specific physical keys, such as Volume keys, Power key, Back key, Home key, and Activities key. These keys respond to a press. The same keys have particular functionality on the nature of the press. The volume key on a Single press increases or decreases the volume by some amount. Similarly, the Powe
3 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. In this article, we will show you how you could start a New Activity using Intent in Android using Jetpack Compose. Follow
4 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose. Note: If you are
9 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose. Note: If you
9 min read
Horizontal ListView in Android using Jetpack Compose
Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only avai
6 min read
Material Design Text Input Field using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
3 min read
How to Remove TextField Padding in Android using Jetpack Compose?
In Android Jetpack Compose, a TextField is used to take input from the user in the form of text. TextField when in focus or when clicked invokes a soft keyboard. In general, TextField is highly attributed for a better feel and appearance. However, we can use a pre-developed TextField, named BasicTextField, which has no attributes like that of a reg
3 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functio
3 min read
Play Audio in Android using Jetpack Compose
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a MediaPlayer, playing, pausing, starting, and stopping the media. In this article, we will show you how you could play an Audio File on Android using Jetp
3 min read
Curved Text in Android using Jetpack Compose
In Android, there are no inbuilt schemes to implement designed text like the word art, which is available in applications like MS Word. We can always refer to or download such schemes like designed font faces to implement designed text. However, it is also possible to natively build (building from scratch) such designed texts in an Android Project.
3 min read
How to Get Screen Width and Height in Android using Jetpack Compose?
Android applications are being developed for different device orientations to support a huge range of devices. So that users with different device size configurations can use the application. Many applications need to get the height and width of the device screen to create UI. In this article, we will take a look at How to get Screen Width and Heig
5 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is used which is used to read pdf and get the data from
6 min read
TopAppBar in Android using Jetpack Compose
TopAppBar is similar to that of the Action Bar widget in Android. This is one of the most UI components in Android. The action bar is used to represent the app name and action items in Android. In this article, we will take a look at the implementation of the TopAppBar in Android using Jetpack compose. Attributes of Top App Bar WidgetAttributes Des
3 min read
How to Draw Track on Google Maps in Android using Jetpack Compose?
In many android apps, we have seen that there is a route marker from a source location to the destination location. In this article, we will take a look at How we can draw a track on Google Maps in Android using Jetpack Compose. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo create a new project in Android Studio please
6 min read
Material Design Buttons using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
4 min read
Snackbar in Android using Jetpack Compose
Prerequisites: Snackbar Material Design Components in AndroidJetpack Compose in Android Snackbar is a lightweight widget and they are used to show messages at the bottom of the application. It was introduced with the Material Design library as a replacement for a Toast. In this article, we will explain how you can create a Snackbar using Jetpack Co
2 min read
Custom Chips using Jetpack Compose in Android
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android's Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going
5 min read
How to make Text Selectable in Android using Jetpack Compose?
By default, Composable Texts are not selectable which means users cannot copy text from your application, and to enable text selection you need to wrap the text elements into Selection Container. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build.
2 min read
Article Tags :