保存海康的视频成MP4格式的视频,最后无法在网页上播放,或者干脆本地无法打开;
既然使用ffmpeg作为视频转码工具,首先需要有这个;
idea下FFmpeg存放的位置,或者可以自定将其配置到环境变量中,我这边是为了防止在其他地方部署每次都要配置这个环境变量,所以直接放在了资源文件夹下面;
public class VideoUtils {
private static Logger log = Logger.getLogger(VideoUtils.class);
private static String ffmpegPath = null;
// 获取FFmpeg所在路径,这边是直接丢在Resource文件夹下面ffmpeg文件夹下
public static String getFFPath() {
if (ffmpegPath != null) {
return ffmpegPath;
}
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//获取所有匹配的文件
Resource resource = resolver.getResource("ffmpeg/ffmpeg.bat");
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
InputStream stream = resource.getInputStream();
String targetFilePath = resource.getFile().getParent();
return targetFilePath;
} catch (IOException e) {
return null;
}
}
public static boolean processMP4(String inputPath, String outputPath) {
long start = System.currentTimeMillis();
log.info("接收到视频文件,开始对文件进行转码...");
if(StringUtils.isBlank(inputPath)){
return null;
}
// 构建 ffmpeg -i 1.mp4 -c copy -an 2.mp4
StringBuilder commend = new StringBuilder();
String ffPath = getFFPath();
// commend.append("cmd /k \"cd "+ ffPath+" ");//可以设置环境变量从而省去这行
commend.append(" ffmpeg ");
commend.append(" -i ");
commend.append(inputPath);
commend.append(" -c copy ");
commend.append(" -an ");
commend.append(outputPath);
try {
File dir = new File(ffPath);
String[] cmd = new String[]{"cmd", "/c", commend.toString()};
Process p = Runtime.getRuntime().exec(cmd, null, dir);
//1. start
BufferedReader buf = null; // 保存ffmpeg的输出结果流
String line = null;
//read the standard output
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb = new StringBuffer();
while ((line = buf.readLine()) != null) {
// 输出到控制台,这部分都可以删除
System.out.println(line);
sb.append(line);
continue;
}
int ret = p.waitFor();//这里线程阻塞,将等待外部转换进程运行成功运行结束后,才往下执行
//1. end
log.info("结束视频转码,共耗时:" + (System.currentTimeMillis() - start) +"耗秒");
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
// 删除原始文件
public static void delOriginalFile(String filePath) {
File file = new File(filePath);
if (file.exists())
file.delete();
}
public static void main(String[] args) {
String input = "E:\\202110091408390859.mp4";
String output = "E:\\new3.mp4";
System.out.println(processMP4(input, output));
delOriginalFile(input);
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容