安卓-音频焦点
音频焦点
是什么
一个安卓系统肯定会有多个音源,音频焦点是用来处理这些音源的冲突
eg 在播放网易云的时候 打开抖音 网易云会自动暂停 并且网易云有提醒 其实是网易云做了处理
发者需要明确编写代码来请求和处理音频焦点的变化。
怎么做
主要涉及这2个对象
kotlin
private var audioFocusRequest: AudioFocusRequest? = null
private var audioManager: AudioManager? = null
主要的要做的工作有3个
1.当应用开始播放音频时,开发者需要通过 AudioManager
请求音频焦点:
kotlin
if (audioFocus) { //audioFocus是自定义bool
doPlaying()
}else {
val result = audioManager!!.requestAudioFocus(audioFocusRequest!!)
if (result == AudioManager.AUDIOFOCUS_GAIN) {
doPlaying()
audioFocus = true
}
}
2.处理音频焦点变化:
就是实现OnAudioFocusChangeListener 并且set进去
kotlin
val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange: Int ->
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
audioFocus = true
play()
Log.d(TAG, "AUDIO_FOCUS_GAIN")
}
AudioManager.AUDIOFOCUS_LOSS -> {
audioFocus = false
pause()
Log.d(TAG, "AUDIO_FOCUS_LOSS")
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
audioFocus = false
pause()
Log.d(TAG, "AUDIO_FOCUS_LOSS_TRANSIENT")
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ->
Log.d(TAG, "AUDIO_FOCUS_LOSS_TRANSIENT_CAN_DUCK")
}
}
audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build())
.setOnAudioFocusChangeListener(audioFocusChangeListener)
.build()
3.放弃音频焦点: 当你的应用不再需要播放音频时
音乐暂停 或者应用销毁等等
kotlin
audioManager!!.abandonAudioFocusRequest(audioFocusRequest!!)