Search code examples
androidandroid-mediaplayer

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);
mPlay.start();

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


Solution

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

    http://developer.android.com/training/managing-audio/audio-focus.html

    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.
                                 AudioManager.STREAM_MUSIC,
                                 // Request permanent focus.
                                 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        // Start playback.
        Log.i(TAG, "...audiofocus granted....");
        MediaPlayer mPlay = MediaPlayer.create(this, R.raw.sound);
        mPlay.start();
    }
    
    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......");
                //am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
                am.abandonAudioFocus(afChangeListener);
                // Stop playback
            }
        }
    };
    

    Hope it helps someone.