遇到了需要点击不同的条目播放不同的音频,实现下方工具类记录一下。
准备工作
添加exoplayer依赖,考虑到exoplayer可以较好的播放音视频,api简单一些。
implementation 'com.google.android.exoplayer:exoplayer:2.13.3'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
工具类实现
object ExoPlayer : DefaultLifecycleObserver {
private var playStartedCallBack: (() -> Unit)? = null
private var playEndedCallBack: (() -> Unit)? = null
private var player: SimpleExoPlayer? = null
private val playerEventListener = object : Player.EventListener {
override fun onPlaybackStateChanged(state: Int) {
super.onPlaybackStateChanged(state)
when (state) {
Player.STATE_BUFFERING -> {
playStartedCallBack?.invoke()
}
Player.STATE_ENDED -> {
playEndedCallBack?.invoke()
}
else -> {}
}
}
}
fun play(
appContext: Context,
playerUrl: String,
isRepeat: Boolean = false,
startCallBack: (() -> Unit)? = null,
endCallBack: (() -> Unit)? = null
) {
if (playerUrl.isBlank()) {
Log.d("ExoPlayer", "play() playerUrl isBlank")
return
}
playStartedCallBack = startCallBack
playEndedCallBack = endCallBack
val musicPlayer = if (null == player) {
SimpleExoPlayer.Builder(appContext).build().apply {
addListener(playerEventListener)
}.also {
player = it
}
} else {
player!!
}
musicPlayer.clearMediaItems()
val mediaItem = MediaItem.fromUri(playerUrl)
musicPlayer.setMediaItem(mediaItem)
musicPlayer.repeatMode = if (isRepeat) {
Player.REPEAT_MODE_ONE
} else {
Player.REPEAT_MODE_OFF
}
musicPlayer.prepare()
musicPlayer.play()
}
fun isPlaying(): Boolean {
return player?.isPlaying ?: false
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
player?.let { musicPlayer ->
if (musicPlayer.repeatMode == Player.REPEAT_MODE_ONE
&& musicPlayer.playbackState == Player.STATE_READY
) {
musicPlayer.play()
}
}
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
player?.pause()
}
override fun onDestroy(owner: LifecycleOwner) {
playStartedCallBack = null
playEndedCallBack = null
player?.clearMediaItems()
player?.removeListener(playerEventListener)
player?.release()
player = null
super.onDestroy(owner)
}
}