Up and down volume of an audio channel with the physical buttons on Android

2

I would like to synchronize the physical buttons of volume up and down synchronized with a specific audio channel.

When clicking, the dialogue of the image will be shown, with the seekbar icon and increase or decrease the volume.

    
asked by Webserveis 15.05.2017 в 15:40
source

2 answers

3

Fixed!

After the answer of the partner @Jorgesys I started to investigate more the possibilities of the FLAGS of the AudioManager.

With the FLAG_SHOW_UI flag, you can display the system's Toast with the slide bar to increase or decrease the volume.

For the default channel

Without specifying the audio channel of the volume, it obtains by default the established system:

To upload: audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);

To go down audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);

For a specific channel

To assign the specific audio channel, the adjustStreamVolume(canal_de_audio,...)

method is used
int streamType = AudioManager.STREAM_MUSIC;

To increase the volume of the music channel:

audioManager.adjustStreamVolume(streamType,
        AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);

To lower the volume of the music channel:

audioManager.adjustStreamVolume(streamType,
        AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);

Final code

private int streamType = AudioManager.STREAM_MUSIC;
...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

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

    if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)){
        audioManager.adjustStreamVolume(streamType,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
    }else if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
        audioManager.adjustStreamVolume(streamType,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
    }
    return true; // super.dispatchKeyEvent(event);
}
    
answered by 15.05.2017 в 17:39
1

One approach is to detect an action on the buttons to modify the volume and use the AudioManager :

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

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

    if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)){
        Log.i(TAG, "VOLUME UP!");
        audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
    }else if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
        Log.i(TAG, "VOLUME DOWN!");
        audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
    }
    return true;
}
    
answered by 15.05.2017 в 16:22