Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Control Media Volume Using Android SeekBar?

How to Control Media Volume Using Android SeekBar?

An Android SeekBar is a user interface element that allows the user to adjust a value within a specific range by dragging a thumb along a horizontal track. SeekBars are commonly used to adjust settings such as volume or brightness or to select a value from a continuous range such as a range of dates or a range of values. In this tutorial, we learn How to control media volume using Android SeekBar, To control media volume using an Android SeekBar, you can follow these steps:

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. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

When your Android Studio Setup is ready, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Add a SeekBar view to your layout file. To know more about SeekBar and How to create a SeekBar in Android please refer to Android | Creating a SeekBar.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="300dp"
        android:layout_height="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Step 3: Working with the MainActivity File

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

  • In the MainActivity.java file, Initialize the SeekBar and also get the audio manager services in your Activity.
  • Set the maximum value of the SeekBar to the maximum volume of the device. You can get the maximum volume using AudioManager.getStreamMaxVolume().
  • Set the current progress of the SeekBar to the current volume of the device. You can get the current volume using AudioManager.getStreamVolume().
  • Set an OnSeekBarChangeListener on the SeekBar to listen for changes to the SeekBar progress.
  • In the onProgressChanged() method of the OnSeekBarChangeListener, set the device’s volume to the progress of the SeekBar using AudioManager.setStreamVolume().

Java




import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initialize the SeekBar in your Activity or Fragment:
        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
  
        // Get the audio manager
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
  
        // Set the maximum volume of the SeekBar to the maximum volume of the MediaPlayer:
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar.setMax(maxVolume);
  
        // Set the current volume of the SeekBar to the current volume of the MediaPlayer:
        int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar.setProgress(currVolume);
  
        // Add a SeekBar.OnSeekBarChangeListener to the SeekBar:
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,i,0);
            }
  
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // Do Nothing
            }
  
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // Do Nothing
            }
        });
    }
}


Kotlin




import android.media.AudioManager
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initialize the SeekBar in your Activity or Fragment:
        val seekBar = findViewById<View>(R.id.seekBar) as SeekBar
  
        // Get the audio manager
        val audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
  
        // Set the maximum volume of the SeekBar to the maximum volume of the MediaPlayer:
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        seekBar.max = maxVolume
  
        // Set the current volume of the SeekBar to the current volume of the MediaPlayer:
        val currVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        seekBar.progress = currVolume
  
        // Add a SeekBar.OnSeekBarChangeListener to the SeekBar:
        seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0)
            }
  
            override fun onStartTrackingTouch(seekBar: SeekBar) {
                // Do Nothing
            }
  
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                // Do Nothing
            }
        })
    }
}


Output: Run on Emulator

Increase or Decrease the Volume with the Volume Bar UI:

The only change we have to make is to pass the parameter AudioManager.FLAG_SHOW_UI instead of 0 as the boolean value in the onProgressChanged method.

Java




import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initialize the SeekBar in your Activity or Fragment:
        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
  
        // Get the audio manager
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
  
        // Set the maximum volume of the SeekBar to the maximum volume of the MediaPlayer:
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar.setMax(maxVolume);
  
        // Set the current volume of the SeekBar to the current volume of the MediaPlayer:
        int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar.setProgress(currVolume);
  
        // Add a SeekBar.OnSeekBarChangeListener to the SeekBar:
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, AudioManager.FLAG_SHOW_UI);
            }
  
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // Do Nothing
            }
  
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // Do Nothing
            }
        });
    }
}


Kotlin




import android.media.AudioManager
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initialize the SeekBar in your Activity or Fragment:
        val seekBar = findViewById<View>(R.id.seekBar) as SeekBar
  
        // Get the audio manager
        val audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
  
        // Set the maximum volume of the SeekBar to the maximum volume of the MediaPlayer:
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        seekBar.max = maxVolume
  
        // Set the current volume of the SeekBar to the current volume of the MediaPlayer:
        val currVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        seekBar.progress = currVolume
  
        // Add a SeekBar.OnSeekBarChangeListener to the SeekBar:
        seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, AudioManager.FLAG_SHOW_UI)
            }
  
            override fun onStartTrackingTouch(seekBar: SeekBar) {
                // Do Nothing
            }
  
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                // Do Nothing
            }
        })
    }
}


Output: Run on Emulator

We can clearly see that when we are sliding the cursor on the SeekBar the media volume is decreasing/increasing according to the movement.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments