package com.ydl.media.audio.manager

import android.content.Context
import android.content.Context.AUDIO_SERVICE
import android.media.AudioManager
import com.ydl.media.audio.AudioPlayer

/**
 * Created by haorui on 2019-10-27 .
 * Des: 音频焦点管理器
 */
class AudioFocusManager(context: Context) : AudioManager.OnAudioFocusChangeListener {
    private val audioManager: AudioManager
    private var isPausedByFocusLossTransient: Boolean = false

    init {
        audioManager = context.getSystemService(AUDIO_SERVICE) as AudioManager
    }

    fun requestAudioFocus(): Boolean {
        return audioManager.requestAudioFocus(
            this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN
        ) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
    }

    fun abandonAudioFocus() {
        audioManager.abandonAudioFocus(this)
    }

    override fun onAudioFocusChange(focusChange: Int) {
        when (focusChange) {
            // 重新获得焦点
            AudioManager.AUDIOFOCUS_GAIN -> {
                if (isPausedByFocusLossTransient) {
                    // 通话结束，恢复播放
                    AudioPlayer.get().startPlayer()
                }

                // 恢复音量
                AudioPlayer.get().mediaPlayer!!.setVolume(1f, 1f)

                isPausedByFocusLossTransient = false
            }
            // 永久丢失焦点，如被其他播放器抢占
            AudioManager.AUDIOFOCUS_LOSS -> AudioPlayer.get().pausePlayer()
            // 短暂丢失焦点，如来电
            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                AudioPlayer.get().pausePlayer(false)
                isPausedByFocusLossTransient = true
            }
            // 瞬间丢失焦点，如通知
            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ->
                // 音量减小为一半
                AudioPlayer.get().mediaPlayer!!.setVolume(0.5f, 0.5f)
        }
    }
}
