ffmpeg的简单实用
1、截取视频某一帧图片作为视频封面
public static String ffmpegPath = "E:\\99demo\\视频播放\\ffmpeg-20171225-be2da4c-win64-static\\bin\\";
public static void videoCatchImg(String videoPath) {
File file = new File(videoPath);
List<String> commands = new ArrayList<>();
commands.add(ffmpegPath+"ffmpeg");
//输入文件
commands.add("-i");
commands.add(videoPath);
//输出文件若存在可以覆盖
commands.add("-y");
//指定图片编码格式
commands.add("-f");
commands.add("image2");
//设置截取视频第3秒时的画面
commands.add("-ss");
commands.add("3");
//截取的图片路径
commands.add(videoPath.substring(0, videoPath.lastIndexOf(".")) + "_cover.jpg");
System.out.println("commands:"+commands);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
builder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
2、将视频转换为MP4格式
public static int checkContentType(String inputPath) {
String type = inputPath.substring(inputPath.lastIndexOf(".") + 1).toLowerCase();
// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等),如果是MP4就先不转化了
if (type.equals("mp4")) {
return 9;
} else if (type.equals("avi")) {
return 0;
} else if (type.equals("wmv")) {
return 0;
} else if (type.equals("3gp")) {
return 0;
} else if (type.equals("mov")) {
return 0;
} else if (type.equals("mp9")) {
return 0;
} else if (type.equals("asf")) {
return 0;
} else if (type.equals("asx")) {
return 0;
} else if (type.equals("flv")) {
return 0;
}
// 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
else if (type.equals("wmv9")) {
return 1;
} else if (type.equals("rm")) {
return 1;
} else if (type.equals("rmvb")) {
return 1;
}
return -1;
}
public static boolean processMp4(String inputPath,String outputPath,String filename) {
List<String> command = new ArrayList<String>();
command.add(ffmpegPath + "ffmpeg");
command.add("-i");
command.add(inputPath);
command.add("-c:v");
command.add("libx264");
command.add("-mbd");
command.add("0");
command.add("-c:a");
command.add("aac");
command.add("-strict");
command.add("-2");
command.add("-pix_fmt");
command.add("yuv420p");
command.add("-movflags");
command.add("faststart");
command.add(outputPath + filename);
try {
Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
new PrintStream(videoProcess.getErrorStream()).start();
new PrintStream(videoProcess.getInputStream()).start();
videoProcess.waitFor();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}