2

I am developing an Android alarm clock app and I am using the STREAM_ALARM for playing the alarm audio. When I plug in headphones during the alarm playing the audio, the audio starts playing in the headphones but also continues playing in the speaker. But I want to silence the speaker so that the user can plug in his headphones and continue listening to the audio without interrupting any people around him. This might be unusual behavior, but it's very important for this specific alarm clock app.

Maybe I could use STREAM_MUSIC, but:

  • The docs say that Unless your app is an alarm clock, you should play audio using the STREAM_MUSIC stream.
  • If the alarm starts ringing and headphones are already plugged in, I do need it to play through the speaker. STREAM_MUSIC does not do this. There might be workarounds, but I need this 100% reliable, so it'd be better to make a workaround for silencing the speaker when needed than a workaround for making it loud when needed.
  • I am not sure what other consequences it might have, it doesn't seem safe.

So, is there any option to force the speaker to be silent? Using some reflection maybe?

I was also considering changing the stream type on the ActionHeadsetPlug to STREAM_MUSIC, but it requires stopping the audio, recreating the MediaPlayer instance, seeking to the previous position, rebinding any events, other logic etc.. a lot of work for my use case. Silencing the speaker would definitely be better if it's possible.

David Riha
  • 1,368
  • 14
  • 29
  • 1
    Playing the audio in both the loudspeaker and the headphones is the intended behavior for `STREAM_ALARM` (or at least it used to be back when I worked with this stuff at Sony). The reason being that you should hear the alarm even if you don't have the headphones in your ears but you left them plugged into your phone. If you don't want this behavior, use a different stream type (e.g. `STREAM_MUSIC`). – Michael Mar 08 '19 at 10:31
  • @Michael Yes, I know it's intended and I understand the reason, I am looking for a way to override it on a headphones plugged-in event but keep it through the speaker if the headphones were already plugged when the alarm started ringing. I updated the question, please check it now :) – David Riha Mar 08 '19 at 10:50
  • 1
    Well, the behavior of `STREAM_ALARM` is what it is. If you don't want that behavior then you should be using some other more suitable stream type. For example, when starting playback, check whether there are headphones attached and select either `STREAM_ALARM` or `STREAM_MUSIC` based on that. – Michael Mar 08 '19 at 11:16

0 Answers0