4
votes

In my application I have overridden the onKeyDown() and onKeyUp() functions in order to capture volume keys events. I use such events in order to control my application volume. I use the music stream to play my sounds. When detecting an event like this I also show a custom toast (similar to the one shown by Android). The problems I'm facing with this take are:

  1. Android always plays a sound on volume keys events
  2. That sound is played always at the same intensity.

What I'd like is to control the intensity at which the default sound is played (also the stream on which is played) in the following way: a louder sound for a higher volume and a lower sound for a low volume, if this is possible. Or a way to disable playing that default sound and play my custom sound at the intensity I just set.

2

2 Answers

9
votes

Actually the sound is played on onKeyUp(...), so you can simply overload the method in your activity when it gets called for the volume keys :

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
       return true;
    }
    return super.onKeyUp(keyCode, event);
}

This worked for me :)

0
votes

It's strange cause I was writing similar functionality and Android seems to play louder sounds when you rise stream volume.

am.setStreamVolume(AudioManager.STREAM_MUSIC, progress,AudioManager.FLAG_PLAY_SOUND);

Thats what I used in my application. am is instance of AudioManager you can get by writing:

AudioManager am = (AlarmManager) getSystemService(AUDIO_SERVICE);

To disable sound you can replace AudioManager.FLAG_PLAY_SOUND with "0" value what should disable it.

I'm not sure if it is possible to replace those sound in AudioManager but you can play those custom sounds with MediaPlayer inside of your onKeyDown methods.

Hope this helps.