2021SC@SDUSC
一、背景
为了提高我们在项目中的参与度,不局限于读代码和分析代码,老师给我们每个人都布置了相应的项目任务,让我们也能参与进项目的开发,进一步加强我们对项目的理解。
我被分配到的任务是:后台医护人员上传视频资料到老年健康知识图谱网站的数据库中时,视频文件的大小,分辨率,帧率和编码格式存在差异,我需要将医护人员上传的视频的格式进行统一。
二、代码实现
ffmpeg工具
1,下载地址:http://www.ffmpeg.org/download.html(我下载的是Windows版本的)
2,将压缩包解压到一个文件夹:
转换类
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class VideoTransferUtil {
//ffmpegPath为FFmpeg解压后的路径
//本项目中的路径为:D:\z\ffmpeg-2021-10-30-git-d92fdc7144-essentials_build\bin\ffmpeg.exe
private static String ffmpegPath="D:\\z\\ffmpeg-2021-10-30-git-d92fdc7144-essentials_build\\bin\\ffmpeg.exe";
/**
* oldFilePath:原视频文件路径
* outPutPath:转换后新视频文件存放路径
* type:为int类型,决定文件转换质量(可自定义,在transfer()中修改)
* resolution:为int类型,决定分辨率等级(可自定义,在transfer()中修改)
* resolution=0:(180p)320x180
* resolution=1:(360p)640x360
* resolution=2:(540p)960x540
* resolution=3:(720p)1280x720
* resolution=4:(900p)1600x900
* resolution=5:(1080p)1920x1080
* resolution=6:(1260p)2240x1260
* resolution=7:(2k)2560x1440
* resolution=8:(4k)3840x2160
* @throws IOException
* @throws InterruptedException
*/
public static boolean transfer(String oldFilePath,String outPutPath,int type,int resolution) throws IOException, InterruptedException {
List<String> command = new ArrayList<String>();
String Resolution = null;
switch(resolution) {
case 0:
Resolution="320x180";
break;
case 1:
Resolution="640x360";
break;
case 2:
Resolution="960x540";
break;
case 3:
Resolution="1280x720";
break;
case 4:
Resolution="1600x900";
break;
case 5:
Resolution="1920x1080";
break;
case 6:
Resolution="2240x1260";
break;
case 7:
Resolution="2560x1440";
break;
case 8:
Resolution="3840x2160";
break;
}//可自定义分辨率
command.add(ffmpegPath); // 添加转换工具路径
command.add("-i"); // 该参数指定要转换的文件
command.add(oldFilePath);
if(type == 0) {
command.add("-qscale"); // 该参数指定转换的质量
command.add("4");
}else {
command.add("-qmin");// 该参数指定转换的质量
command.add("4");
}//可自定义自己需求的转换质量
command.add("-r"); // 该参数设置帧速率
command.add("15");
command.add("-s"); // 该参数设置分辨率
command.add(Resolution);
command.add("-y"); // 该参数指定将覆盖已存在的文件
command.add(outPutPath);
if (null == command || command.size() == 0) return false;
Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
videoProcess.getInputStream().close();
int exitcode = videoProcess.waitFor();
if (exitcode == 1) return false;
return true;
}
}
这个类中的 transfer()方法最终会使用ffmpeg工具进行视频转换。
测试类
import java.io.File;
import java.io.IOException;
public class text {
public static void main(String[] args) throws IOException, InterruptedException {
boolean t;
String newpath;
int i = 0;
File file = new File("D:\\z\\video\\");//对该路径文件夹中的所有视频进行转换
File[] files = file.listFiles();
for (File f : files) {
newpath = "D:\\z\\video_new\\"+f.getName();
t=VideoTransferUtil.transfer(f.getPath(), newpath, 0, 5);
i++;
if(t) {
System.out.println("第"+i+"个文件转换成功");
}else {
System.out.println("第"+i+"个文件转换失败");
}
}
System.out.println("视频文件转成功");
}
}
该测试类实现了对一个文件夹中的所有视频进行批量转换,并将转换成功的视频存放在指定文件夹中(注意文件夹中只能有视频)。