Home » Android » how to increase and decrease the volume programmatically in android

how to increase and decrease the volume programmatically in android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I created the music player app and i want to set the volume up/down programmatically .

I want to implement two another Button for increase/decrease of volume and set to the media player .

Please help me in accessing volume up/down in android.

Activity Codes :

control = (ImageView) findViewById(R.id.control);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
control.setOnClickListener(pausePlay);
control.setBackgroundResource(R.drawable.pause);
control id is my play and pause button :
{
            // TODO Auto-generated method stub
            // TODO Auto-generated method stub

            if (playPause) {
                control.setBackgroundResource(R.drawable.play);
                if (mediaPlayer.isPlaying())
                    mediaPlayer.pause();
                media.stop();
                intialStage = false;
                playPause = false;

            } else {
                control.setBackgroundResource(R.drawable.pause);
                if (intialStage) {
                    new Player()
                            .execute("http://streaming.shoutcast.com/MUKILFMRADIO");
                } else {
                    if (!mediaPlayer.isPlaying())
                        mediaPlayer.start();
                }
                playPause = true;
            }
}

Layout codes:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center">
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/control1"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/decrement"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/control"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/play"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/control2"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:background="@drawable/increment"
        android:layout_above="@+id/latestAddedSongs"
        android:layout_alignEnd="@+id/musicArtistName" />
</LinearLayout>

Give a link or tutorial about Mute/UnMute and Volume Up/Down in android Programmatically.

How to&Answers:

Create an object for audio manager

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);


Button upButton = (Button) findViewById(R.id.upButton);
        upButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//To increase media player volume               
                audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
            }
        });

        Button downButton = (Button) findViewById(R.id.downButton);
        downButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//To decrease media player volume
                audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);             
            }
        });

The above example used Button label

for volume up and down
code

@Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (action == KeyEvent.ACTION_DOWN) {
                    audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (action == KeyEvent.ACTION_DOWN) {
                    audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                }
                return true;
            default:
                return super.dispatchKeyEvent(event);
        }
    }

Answer:

Try below code

audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
  @Override
  public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) {
    textview.setText("Media Volume : " + newVolume);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {}
});

Answer:

Following up on solution of jesu, if you want to change volume within Service instead of Activity, replace:

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

with:

AudioManager audioManager;
audioManager = (AudioManager) YourServiceName.this.getSystemService(Context.AUDIO_SERVICE);

Answer:

if your type is AudioManager.STREAM_MUSIC: use this code ,follow phone volume button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            AudioManager.ADJUST_RAISE,
            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            AudioManager.ADJUST_LOWER,
            AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        break;
    }
    return super.onKeyDown(keyCode, event);
}

Answer:

Below code worked great

There are several streams available in Android using which audio can be managed

 /** The audio stream for phone calls */
    public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
    /** The audio stream for system sounds */
    public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
    /** The audio stream for the phone ring */
    public static final int STREAM_RING = AudioSystem.STREAM_RING;
    /** The audio stream for music playback */
    public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
    /** The audio stream for alarms */
    public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
    /** The audio stream for notifications */
    public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
    /** @hide The audio stream for phone calls when connected to bluetooth */
    public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
    /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
    public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
    /** The audio stream for DTMF Tones */
    public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
    /** @hide The audio stream for text to speech (TTS) */
    public static final int STREAM_TTS = AudioSystem.STREAM_TTS;

Depending on your need you can change the stream here is STREAM_MUSIC example :

You can get constant value using refelction from AudioSytem class:

 private int getStreamType(String streamName) {
        final String streamSourceClassName = "android.media.AudioSystem";
        int streamType = 0;
        try {
            streamType = (int) Class.forName(streamSourceClassName).getDeclaredField(streamName).get(null);
        } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return streamType;
    }


audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
  @Override
  public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) {
    textview.setText("Media Volume : " + newVolume);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {}
});