基于版本
api 'com.google.android.exoplayer:exoplayer:2.17.0'
xml中使用布局
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/playerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:surface_type="texture_view"
app:resize_mode="fill"
/>
播raw文件
val rawSource = RawResourceDataSource(this)
rawSource.open(DataSpec(RawResourceDataSource.buildRawResourceUri(R.raw.test)))
val player = ExoPlayer.Builder(this).build()
viewBinding.playerView.player = player
player.repeatMode = Player.REPEAT_MODE_ALL
player.setMediaItem(MediaItem.fromUri(rawSource.uri!!))
player.prepare()
player.play()
播网络视频
val player = ExoPlayer.Builder(this).setMediaSourceFactory(DefaultMediaSourceFactory(VideoUtil.getCacheFactory(this))).build()
player.repeatMode = Player.REPEAT_MODE_ALL
viewBinding.playerView.player = player
viewBinding.playerView.useController = false
player.addListener(object : Player.Listener{
override fun onPlaybackStateChanged(playbackState: Int) {
super.onPlaybackStateChanged(playbackState)
logE(TAG,"player State : $playbackState")
when(playbackState){
Player.STATE_IDLE -> {
}
Player.STATE_READY -> {
viewBinding.imgLoading.Gone()
}
}
}
override fun onPlayerError(error: PlaybackException) {
super.onPlayerError(error)
logE(TAG,"onPlayerError${error}")
}
override fun onPlayerErrorChanged(error: PlaybackException?) {
super.onPlayerErrorChanged(error)
logE(TAG,"onPlayerErrorChanged${error}")
}
})
player.setMediaItem(MediaItem.fromUri(bean.avatarAnimatedImage))
player.prepare()
player.play()
缓存工厂设置
object VideoUtil {
private var cacheFactory : DataSource.Factory? = null
fun getCacheFactory(ctx: Context): DataSource.Factory {
if(cacheFactory == null) {
var downDirectory = File(ctx.filesDir, "videos")
var cache = SimpleCache(
downDirectory,
LeastRecentlyUsedCacheEvictor(1024L * 1024L * 512L),
StandaloneDatabaseProvider(ctx)
)
cacheFactory = CacheDataSource.Factory().setCache(cache).setUpstreamDataSourceFactory(
DefaultHttpDataSource.Factory())
}
return cacheFactory!!
}
}
|