**需要注意,ffmpeg 命令 -s 指定了宽高后,如果为奇数宽高(101*101),则裁剪后的视频无法正常播放,不加-s则ffmpeg自动-1处理;**
private void cutVideo() throws Exception{
try {
String ffmpegSource ="/opt/xxxxx/ffmpeg/ffmpeg";// todo ffmpeg程序绝对路径
String videoSource = "/opt/xxxxxx/xxx_source.mp4"; //todo 视频源绝对路径
String videoTarget = "/opt/xxxxxx/xxx_target.mp4"; // todo 视频目标绝对路径
//执行程序拼接命令
List<String> command = new ArrayList<>();
command.add(ffmpegSource);
command.add("-i");
command.add(videoSource);
command.add("-vf");
int cutVideoWidth = 100; // todo 要裁的实际宽
int cutVideoHeight = 100; // todo 要裁的实际高
int leftTopX = 0; //todo 要裁的部分左上角x坐标
int leftTopY = 0; //todo 要裁的部分左上角y坐标
StringBuffer tmp = new StringBuffer();
tmp.append("crop=w=");
tmp.append(cutVideoWidth);
tmp.append(":h=");
tmp.append(cutVideoHeight);
tmp.append(":x=");
tmp.append(leftTopX);
tmp.append(":y=");
tmp.append(leftTopY);
String vfStr = tmp.toString();
command.add("-vf");
command.add(vfStr);
command.add("-r");
command.add("25");
command.add("-y");
command.add("-s");
String sStr = cutVideoWidth + "*" + cutVideoHeight;
command.add(sStr);
command.add(videoTarget);
ProcessBuilder builder = new ProcessBuilder();
builder.command(command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuffer message = new StringBuffer();
while ((line = reader.readLine()) != null) {
// ffmpeg 返回信息拼接字符串
message.append(line.trim() + "\r\n");
continue;
}
p.waitFor();
System.out.println(message.toString().trim());
if (reader != null) {
reader.close();
}
p.destroy();
}catch (Exception e){
e.printStackTrace();
// message 就是 ffmpeg报出来的错误信息
}
}
09-22
1050
04-23
2581
07-25
851
03-26
905