Search code examples
androidaudiovideoandroid-video-player

How to pause audio player when video player starts playing?


I am developing an audio player, it can play the audio files in background. My problem is that I need to pause the audio player when video recorder or video player is starts.

Are there any methods to handle this task? For example I have PhoneStateListener to handle the calls. When I received a call or wnat to make a call we can pause the player by using call state. I want the same scenario for the video recorder or video player aswell. When video/recording starts I need to pause my audio player.


Solution

  • You need to detect if there are other apps request audio focus and pause your audio player. AudioManager.OnAudioFocusChangeListener should help. Here is some sample code

    am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    afChangeListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT){
                    // Pause playback
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    // Resume playback 
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                    abandonAudioFocus();
                }
            }
        };
    

    I did not try this code myself, let me know if it helps.