Sushil Sushil - 1 year ago 90
Android Question

Suppressing system audio volume to play notification audio from inside app

My app runs as a service in background and can give notifications based on some events. Currently, to play notification files, I use MediaPlayer in my app :

MediaPlayer mPlay = MediaPlayer.create(this, R.raw.sound);

But, if a song is already playing on the device (Music player, radio etc), and my notification plays when receiving the event, both the sounds (Music audio & notification audio) is heard in parallel.

So, is there a way that I can suppress the system audio volume so that my notification is heard clearly and once notification audio is over, the system audio can playback again?

Thanks for any help

Answer Source

I got the answer to this question in the following link:

We need to request for audio focus (transient/permanent) and then can play the app audio:

AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                             // Use the music stream.
                             // Request permanent focus.

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback.
    Log.i(TAG, "...audiofocus granted....");
    MediaPlayer mPlay = MediaPlayer.create(this, R.raw.sound);

OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
            // Pause playback
            Log.i(TAG, "....audiofocus loss transient in listener......");
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // Resume playback 
            Log.i(TAG, "....audiofocus gain in listener......");
        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            Log.i(TAG, "....audiofocus loss in listener......");
            // Stop playback

Hope it helps someone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download