Dan Dadan Dan Dadan - 1 month ago 26
Android Question

Disable sound when volume keys clicked

In my application I override

volume up
and
volume down
keys. The problem is that when user click one of these two keys, sound is played. I want somehow to disable/mute this sound.

Here is fragment of my code:

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

switch (keyCode) {

case KeyEvent.KEYCODE_VOLUME_DOWN: {
// do something when user click volume down key

return true;
}
case KeyEvent.KEYCODE_VOLUME_UP: {
// do something when user click volume up key

return true;
}

}
return super.onKeyDown(keyCode, event);
}

Answer

I figured it out for myself. There is a way to stop the sound when volume key is pressed. You need to play an empty sound infinitely, so when user click a volume key it is "trying" to change the media volume, so there isn't click sound played. You can download an empty sound by searching for empty sound and then put it in your raw folder in the project. The last step is just to override the volume keys.

Here is the code you need:

Define MediaPlayer variable.

private MediaPlayer infinite_sound;

In onResume() you need to play the empty sound infinitely.

@Override
protected void onResume() {
    super.onResume();

    infinite_sound = MediaPlayer.create(this, R.raw.empty);
    infinite_sound.setLooping(true);
    infinite_sound.start();
}

In onPause() you need to stop the sound.

@Override
public void onPause() {
    super.onPause();

    infinite_sound.release();
}

And finally overriding the actions of the buttons.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    int action = event.getAction();
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_DOWN: {
            // Do something when volume down button is clicked

            return true;
        }
        case KeyEvent.KEYCODE_VOLUME_UP: {
            // Do something when volume up button is clicked

            return true;
        }
    }
}