Search code examples
androidandroid-mediaplayer

Android - Pause MediaPlayer when using the microphone?


How can I pause MediaPlayer streaming when I use microphone on other apps? E.g. Whatsapp or Telegram?


Solution

  • Fixed in this way:

    var audoRecordingCallback = @RequiresApi(Build.VERSION_CODES.N)
    object : AudioRecordingCallback() {
        override fun onRecordingConfigChanged(configs: List<AudioRecordingConfiguration>) {
            super.onRecordingConfigChanged(configs)
            println(configs)
            val isMicOn = try {
                configs.isNotEmpty()
            } catch (e: Exception) {
                false
            }
    
            if (isMicOn) {
                pauseAudioWithoutFocus()
            } else {
                playAudioWithoutFocus()
            }
        }
    }
    
    fun registerMicrophoneListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            this.audioManager.registerAudioRecordingCallback(audoRecordingCallback, null)
        }
    }
    
    fun unregisterMicrophoneListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            this.audioManager.unregisterAudioRecordingCallback(audoRecordingCallback)
        }
    }
    

    And calling registerAudioRecordingCallback and unregisterMicrophoneListener whenever you want