2019-10-16 音视频采坑-视频封面获取+视频压缩
2019-10-16 本文已影响0人
兣甅
1.获取封面,系统方法不靠谱,部分视频会获取失败
部分视频采用MediaMetadataRetriever或者ThumbnailUtils去获取封面,得到的图片为Null,同时无法使用系统播放器去播放该视频,Glide也无法获取到图片缩略图,但是使用ijkplayer是可以播放该视频的。同样的,系统压缩方案:https://github.com/fishwjy/VideoCompressor也会压缩失败
https://blog.csdn.net/yu540135101/article/details/84754432
可以尝试https://github.com/wseemann/FFmpegMediaMetadataRetriever获取封面,比较简洁方便
2.如果有更多需求,可以使用RxFFmpeg
我在项目中用到封面获取和视频压缩(压缩的时间稍微有点长58M压缩为11M花费93秒,相对于之前调查的压缩方案),其使用如下:
//执行命令
fun startCommand (
originFilePath: String,
destFilePath: String
) {
//图片封面获取命令
val command = getCommandFirstFrame(originFilePath, destFilePath)
//视频压缩为30Fps命令
//val command = getCommandCompress(originFilePath, destFilePath)
RxFFmpegInvoke.getInstance()
.runCommandRxJava(command.split(" ").toTypedArray())
.subscribe(object : RxFFmpegSubscriber() {
override fun onFinish() {
Log.e("CASE","压缩成功")
}
override fun onCancel() {
Log.e("CASE","取消压缩")
}
override fun onProgress(
progress: Int,
progressTime: Long
) {
Log.e("CASE","压缩进度:$progress")
}
override fun onError(message: String?) {
Log.e("CASE","压缩失败")
}
})
}
//封面获取命令
@Throws
private fun getCommandFirstFrame(
originPath: String,
outPath: String
): String {
//读取图片尺寸和旋转角度
val mMetadataRetriever = MediaMetadataRetriever()
mMetadataRetriever.setDataSource(originPath)
val videoRotation =
mMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
val videoHeight =
mMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
val videoWidth =
mMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
val width: Int
val height: Int
if (Integer.parseInt(videoRotation) == 90 || Integer.parseInt(videoRotation) == 270) {
//角度不对需要宽高调换
width = videoHeight.toInt()
height = videoWidth.toInt()
} else {
width = videoWidth.toInt()
height = videoHeight.toInt()
}
return String.format(
"ffmpeg -y -i %1\$s -y -f image2 -t 0.001 -s %2\$sx%3\$s %4\$s",
originPath, width, height, outPath
)
}
//文件压缩命令
private fun getCommandCompress(
originPath: String,
outPath: String
): String {
return String.format(
"ffmpeg -y -i %1\$s -b 2097k -r 30 -vcodec libx264 -preset superfast %2\$s",
originPath, outPath
)
}