0

I create a MediaPlayer like in the appended code. Everything works fine, but I've one problem: whenever an alarm is played and I'm connected to headphones, the sound is played on the phone and in the headphones. I would like the phone to be quiet in such a situation.

Actually, if I use the same function to create another music player to play music and set the stream type to AudioManager.STREAM_MUSIC, everything works fine.

I'm getting this behaviour on an android 4.4.4 phone and I know, that this code worked as expected on my old phone... With android 4.3 I think...

    int streamVolume = ((AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager.STREAM_ALARM);
    if (streamVolume != 0)
    {
        mAlarmPlayer = createMediaPlayerIfNeeded(mAlarmPlayer, true, true, false);
        try
        {
            mAlarmPlayer.setDataSource(this, Uri.parse(sound));
            mAlarmPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mAlarmPlayer.setVolume(streamVolume, streamVolume);
            mAlarmPlayer.prepareAsync();
        }
        catch (IOException e)
        {
            Log.e("MusicService", "IOException playing alarm: " + e.getMessage());
            e.printStackTrace();
        }
    }

And here is the create function:

private MediaPlayer createMediaPlayerIfNeeded(MediaPlayer player, boolean setListenerOnPrepared, boolean setListenerOnCompletion, boolean setListenerOnError)
{
    if (player == null)
    {
        player = new MediaPlayer();
        player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        if (setListenerOnPrepared)
            player.setOnPreparedListener(this);
        if (setListenerOnCompletion)
            player.setOnCompletionListener(this);
        if (setListenerOnError)
            player.setOnErrorListener(this);
    }
    else
        player.reset();

    return player;
}
prom85
  • 16,896
  • 17
  • 122
  • 242
  • The point of an alarm or ringtone is that you're supposed to be able to hear it, even if you've got headphones plugged into the phone and aren't wearing the headphones. If you don't want that behaviour, use a different stream, like `STREAM_MUSIC`. – Michael Feb 06 '15 at 08:46
  • I will do it like that... But still, this behaviour changed as it was not like that before... Thanks though – prom85 Feb 06 '15 at 11:10

0 Answers0