播放視頻方法代碼
lateinit var player: ExoPlayer
private fun startVideo(mp4: String) {
player = ExoPlayer.Builder(this).setMediaSourceFactory(
DefaultMediaSourceFactory(VideoUtil.getCacheFactory(this))
).build()
player.repeatMode = Player.REPEAT_MODE_ALL
? ? ? ? root.videos.player =player
? ? ? ? root.videos.useController =false
? ? ? ? player.addListener(object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
super.onPlaybackStateChanged(playbackState)
when (playbackState) {
Player.STATE_IDLE -> {
}
Player.STATE_READY -> {
root.videoProgress.max =player.duration.toInt()
sendMessage()
}
}
}
override fun onVideoSizeChanged(s: VideoSize) {
super.onVideoSizeChanged(s)
if (s.width > s.height) {
val l =root.videos.videoSurfaceView!!.layoutParams as FrameLayout.LayoutParams
l.gravity = Gravity.CENTER
? ? ? ? ? ? ? ? ? ? l.width =root.videos.width
? ? ? ? ? ? ? ? ? ? l.height = (AppTools.dp370 - AppTools.dp20) * (s.width / s.height)
root.videos.videoSurfaceView!!.layoutParams = l
//? ? ? ? ? ? ? ? ? ? layout.width = root.videos.height
//? ? ? ? ? ? ? ? ? ? layout.height = root.videos.width
//? ? ? ? ? ? ? ? ? ? root.videos.videoSurfaceView!!.rotation = 90F
? ? ? ? ? ? ? ? }
}
})
//? ? ? ? player.setMediaItem(MediaItem.fromUri("https://image.xk100.com/test/1100484563391479808.mp4"))
? ? ? ? player.setMediaItem(MediaItem.fromUri(mp4))
player.prepare()
player.play()
}
private fun pause() {
removeMessage()
startTime =player.currentPosition
? ? ? ? player.pause()
}
private fun start() {
sendMessage()
addGone(root.startHint)
player.seekTo(startTime)
player.play()
startTime =0L
? ? }
播放緩存代碼
import android.content.Context
import com.google.android.exoplayer2.database.StandaloneDatabaseProvider
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.upstream.cache.CacheDataSource
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor
import com.google.android.exoplayer2.upstream.cache.SimpleCache
import java.io.File
object VideoUtil {
private var cacheFactory: DataSource.Factory? =null
? ? fun getCacheFactory(ctx: Context): DataSource.Factory {
if (cacheFactory ==null) {
val downDirectory = File(ctx.filesDir, "videos")
val cache = SimpleCache(downDirectory, LeastRecentlyUsedCacheEvictor(1024L *1024L *256L), StandaloneDatabaseProvider(ctx))
cacheFactory = CacheDataSource.Factory().setCache(cache).setUpstreamDataSourceFactory(DefaultHttpDataSource.Factory())
}
return cacheFactory!!
}
}