ExoPlayer播放视频

播放视频方法代码

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!!

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容