tags:

views:

4890

answers:

2

I have an app that plays intermittent sounds while its activity is open, and the user is always expecting it to make these noises, but unfortunately it is constrained by the music stream volume. The options I have discovered are thus:

  1. Adjust the music stream's volume, possibly deafening the user if they happen to be playing music at the time.
  2. Call MediaPlayer.setVolume() which is ineffective if the music stream's volume is 0.
  3. Handle volume button presses myself which presents two issues: volume button presses adjust the ringer volume unless my audio is playing, and I have been as of yet unable to catch the onKey event for a volume button press using my OnKeyListener. If there were some way to force the adjustment to apply to the music stream while my activity has focus, or to just catch the button presses myself this would work.
  4. Play a silent looping piece of audio in the background to keep the music stream in context for volume adjustments.

I think the 3rd option is probably best since it cedes control of the volume to the user, but if there were some way to just override the system volume in a single mediaplayer instance that would work too.

+16  A: 

Got another suggestion via Google Groups that is the platform integrated solution I was looking for and works fine:

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 music volume.

Luke
AGRH! Thanks man, I had exactly same problem (and like idiot spent 2 hours debugging my sound playing code...)
kape123
Thanks. It was difficult to find this by googling. Hell, people on the official android development forum were saying to grab the volume keys. I too thought that was a bad idea, so thanks for finding this.
Martin W
A: 

what's the code of main.class?

I would like to know what is the code for the creation of the "controls" that are used for the volume

Delia
Please don't post new questions as an answer to someone else's question. If you want to ask a new question then go ahead and do it (hit the "Ask Question" button at the top right of the SO window).
Paul R