Search code examples
androidcameramedia-player

Android pause media player when user opens the camera and start recording video


I am developing music play app. When user push my app to background song is playing fine. Now if user opens the camera and starts recording video from camera, I need to pause the song playing from my app .How to do this?


Solution

  • I expect that the app responsible for video recording will request audio focus to notify other apps that they should cease playback. If this is the case, you can implement AudioManager.OnAudioFocusChangeListener like this:

    @Override
    public void onAudioFocusChange(int focusChange)
    {
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
        {
              // pause playback
        }
        else if (focusChange == AudioManager.AUDIOFOCUS_LOSS)
        {
            ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
            doStopPlayback();
        }
        // else if... listen to other types of audio focus loss/ gain
    }
    

    where doStopPlayback() is your method for releasing the MediaPlayer etc.

    See also this guide for media playback.