工作中需要对视频进项压缩,找了一圈没有合适的,官方提供的MediaCodec封装, 转换后的视频绿屏(不知道原因),github上找了好几个不能用,各种bug,最后发现vivo有提供的videoeditor,经过研究,使用方便,唯一缺点就是APK大小增加14M左右。
videoeditor可以对视频做各种处理,特效,裁剪,背景音乐,等等。大家可以自行去官网了解, 本文主要对视频压缩做示例。
fun compressVideo(inputPath: String, mOriginalWidth:Int,mOriginalHeight:Int) {
var outWidth = 0
var outHeight = 0
if (mOriginalWidth > mOriginalHeight) {
//横屏
outWidth = 1280
outHeight = 720
} else {
//竖屏
outWidth = 720
outHeight = 1280
}
/**
* 压缩视频放到应用沙盒目录,上传后删除
*/
val shPath= context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.path
val targetFilePath = "${shPath}/V${System.currentTimeMillis()}.mp4"
val width = outWidth
val height = outHeight
val bitrate = 1 * 4 * 1024 * 1024 // 1B = 8b,压到0.5Mbps 需要乘以4
val fileMaxSize = Int.MAX_VALUE //预留接口,当前没有起作用。
val rotate = 0 //旋转角度,预留接口,当前没有使用。
val audioSampleRate = 48000
val mVideoFactory = VideoFactory()
val project = VideoProject()
val videoClip = Clip.getSupportedClip(inputPath)
project.addClip(videoClip)
mVideoFactory.project = project
mVideoFactory.setEventHandler(object : MyVideoFactoryListener() {
override fun onEncodingProgress(p0: Int, p1: Int) {
//进度
}
override fun onEncodingDone(iserror: Boolean, p1: Int) {
Log.e(TAG, "onEncodingProgress: ${iserror} - ${p1}" )
if (!iserror) {
listener?.onCompressionCompleted(targetFilePath)
mVideoFactory.stopSync()
mVideoFactory.release()
} else {
listener?.onCompressionFailed("压缩失败")
}
}
})
mVideoFactory.export(
targetFilePath,
width,
height,
bitrate,
fileMaxSize.toLong(),
rotate,
audioSampleRate
)
}
官方文档:vivo 视频编辑
3906

被折叠的 条评论
为什么被折叠?



