28

I would like to control media volume with my app using regular volume buttons. The problem is my app is using short sounds, and they might be annoying for the user. You can only adjust media volume while they are playing (for 1 sec) then it starts to adjust ringer volume. How can I make media volume default?

Badr Hari
  • 8,114
  • 18
  • 67
  • 100

3 Answers3

53

In your activity's onCreate() you can do:

setVolumeControlStream(AudioManager.STREAM_MUSIC);
Kevin TeslaCoil
  • 10,037
  • 1
  • 39
  • 33
3

Please don't handle the volume keys yourself - it is almost impossible to guarantee that you won't break the behavior of the volume keys.

Call this API in your onCreate():

setVolumeControlStream(AudioManager.STREAM_MUSIC);

This tells the AudioManager that when your application has focus, the volume keys should adjust the music volume.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
3

I haven't tried this but you should be able to intercept the regular volume buttons by overriding onKeyDown(int keyCode, KeyEvent event) in your Activity. Check for keycodes KEYCODE_VOLUME_UP and KEYCODE_VOLUME_DOWN.

Using AudioManager.setStreamVolume(int, int, int) with STREAM_MUSIC for the streamType parameter should work and if you return true from the onKeyDown(...) method (to indicate you've handled the event), it should prevent the system from adjusting the ringer volume. Make sure you return false for all other keycodes that you're not handling.

Squonk
  • 48,735
  • 19
  • 103
  • 135