美文网首页
ExoPlayer播放视频

ExoPlayer播放视频

作者: 余炳高笔记 | 来源:发表于2024-01-11 17:52 被阅读0次

播放视频方法代码

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

}

}

相关文章

网友评论

      本文标题:ExoPlayer播放视频

      本文链接:https://www.haomeiwen.com/subject/uuitodtx.html