赞
踩
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"
/>
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!! } }
player.addListener(object : Player.Listener{ override fun onVideoSizeChanged(videoSize: VideoSize) { super.onVideoSizeChanged(videoSize) logE("onVideoSizeChanged ${videoSize.width} ${videoSize.height} ; ${viewBinding.playerView.width} ${viewBinding.playerView.height}") if(videoSize.width > videoSize.height){ var layout = viewBinding.playerView.videoSurfaceView!!.layoutParams as FrameLayout.LayoutParams layout.gravity = Gravity.CENTER layout.width = viewBinding.playerView.height layout.height = viewBinding.playerView.width viewBinding.playerView.videoSurfaceView!!.layoutParams = layout viewBinding.playerView.videoSurfaceView!!.rotation = 90F viewBinding } } })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。