Skip to content

Commit

Permalink
优化音频焦点监听
Browse files Browse the repository at this point in the history
  • Loading branch information
maiwenchang committed Jun 5, 2020
1 parent 60917fb commit 4b3a4aa
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.content.Context
import android.media.AudioManager
import android.media.AudioManager.OnAudioFocusChangeListener
import org.salient.artplayer.player.IMediaPlayer
import java.lang.ref.WeakReference

/**
* description: 声音焦点变化管理类
Expand All @@ -14,14 +15,15 @@ import org.salient.artplayer.player.IMediaPlayer
* date: 2020-05-04 10:06 AM.
*/
open class DefaultAudioFocusChangeListener(
private val context: Context,
private val contextReference: WeakReference<Context>,
private val audioManager: IAudioManager,
private val mediaPlayer: IMediaPlayer<*>?
) : OnAudioFocusChangeListener {
private var playOnAudioFocus = true;
override fun onAudioFocusChange(focusChange: Int) {
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
val context = contextReference.get() ?: return
// 重新获得焦点,恢复正常音量,恢复播放
if (playOnAudioFocus && mediaPlayer?.isPlaying != true) {
mediaPlayer?.start();
Expand All @@ -32,6 +34,7 @@ open class DefaultAudioFocusChangeListener(
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
//短暂失去焦点,无须停止播放,只适当降低播放器音量
val context = contextReference.get() ?: return
val duckVolume = getCurrentVolume(context) * 0.8f
mediaPlayer?.setVolume(duckVolume);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import org.salient.artplayer.player.IMediaPlayer
import java.lang.ref.WeakReference

/**
* description: 音频管理
Expand All @@ -24,7 +25,7 @@ open class DefaultAudioManager(context: Context, mediaPlayer: IMediaPlayer<*>?)
.build()
private var audioFocusRequest: AudioFocusRequest? = null

override var onAudioFocusChangeListener: AudioManager.OnAudioFocusChangeListener = DefaultAudioFocusChangeListener(context, this, mediaPlayer)
override var onAudioFocusChangeListener: AudioManager.OnAudioFocusChangeListener = DefaultAudioFocusChangeListener(WeakReference(context), this, mediaPlayer)

override fun mute() {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,9 +320,4 @@ open class VideoView : FrameLayout, IVideoView {
}
}

override fun onDetachedFromWindow() {
removeMediaPlayerObserver(mediaPlayer)
super.onDetachedFromWindow()
}

}

0 comments on commit 4b3a4aa

Please sign in to comment.