添加依赖:
implementation 'com.arthenica:mobile-ffmpeg-full:4.4.LTS'
代码实现:
fun cropMiddleThird(inputPath: String, outputPath: String) {val cmd = arrayOf("-y", // 覆盖输出文件"-i", inputPath,"-filter:v", "crop=iw:ih/3:0:ih/3", // 裁剪中间1/3"-c:a", "copy", // 复制音频流outputPath)FFmpeg.executeAsync(cmd) { executionId, returnCode ->if (returnCode == RETURN_CODE_SUCCESS) {Log.i(TAG, "Video crop completed successfully")} else {Log.e(TAG, "Video crop failed with return code $returnCode")}}}
这段 FFmpeg 命令中的参数含义如下:
-filter:v
参数解析
-
完整形式:
-filter:v
是-filter_complex
的简化形式,专门用于视频滤镜 -
含义:表示后面跟随的是视频滤镜(video filter)设置
-
等价写法:也可以简写为
-vf
(两者完全等效)
crop=iw:ih/3:0:ih/3
滤镜参数解析
这是一个视频裁剪(crop)滤镜,各部分的含义为:
-
iw
:-
表示 input width(输入视频的原始宽度)
-
这里保持原始宽度不变
-
-
ih/3
:-
ih
表示 input height(输入视频的原始高度) -
ih/3
表示将高度裁剪为原始高度的 1/3
-
-
0
:-
表示裁剪区域从水平方向(X轴)的 0 位置开始(即最左侧)
-
-
ih/3
:-
表示裁剪区域从垂直方向(Y轴)的 1/3 高度处开始
-
这样组合起来就是从视频垂直方向的中间 1/3 区域裁剪
-
完整命令含义
ffmpeg -y -i input.mp4 -filter:v "crop=iw:ih/3:0:ih/3" -c:a copy output.mp4
表示:
-
-y
:覆盖输出文件不提示 -
-i input.mp4
:指定输入文件 -
-filter:v "crop=iw:ih/3:0:ih/3"
:-
裁剪视频,保持原始宽度
-
高度取原始高度的 1/3
-
从垂直方向 1/3 处开始裁剪(最终得到的是视频中间的 1/3 部分)
-
-
-c:a copy
:音频流直接复制不重新编码 -
output.mp4
:输出文件路径
其他常见表达式
表达式 | 含义 |
---|---|
iw | 输入视频宽度 |
ih | 输入视频高度 |
ow | 输出视频宽度 |
oh | 输出视频高度 |
dar | 显示宽高比 |
sar | 样本宽高比 |
n | 当前帧序号 |
t | 当前时间戳(秒) |
实际应用示例
如果想裁剪视频顶部 1/3(而不是中间):
crop=iw:ih/3:0:0
如果想裁剪视频右侧 1/3:
crop=iw/3:ih:iw*2/3:0