Search code examples
androidringtonemanager

Android interrupt media player with ringtone manager


I have used ringtonemanager previously in android studio and it seemed to lower the volume of any music that was playing in a different app to play the alert i was trying to play, then once my alert had completed the background music would then come back to normal volume (as the default alarm/notification would do) But now a year or so later im trying to implement this again but my alert cannot be heard over the music playing in Google Play Music.

Is this a change that now requires additional parameters to function as it used to?

Im using:

Uri notification = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
myRM = RingtoneManager.getRingtone(this.getContext(), notification);
myRM.play();

Many Thanks


Solution

  • Handling Changes in Audio Output seems what fits your need.

    In short, you need to request audio focus before starting playing.

    ...
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mAudioManager.requestAudioFocus(null, mStreamType, AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    mRingtone.play();
    

    AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK

    Used to indicate a temporary request of audio focus, anticipated to last a short amount of time, and where it is acceptable for other audio applications to keep playing after having lowered their output level (also referred to as "ducking").

    Remember to release audio focus when finishing..

    if (mRingtone != null && mRingtone.isPlaying()) {
        mRingtone.stop();
    }
    mRingtone = null;
    if (mAudioManager != null) {
        mAudioManager.abandonAudioFocus(null);
    }