java利用ffmpeg追加合并视频文件
首先要用到ffmpeg,可以根据操作系统自行下载每个视频格式要一样,分辨率要一样多个视频地址以list存放,直接上代码
public void mergeVideo(List<String> videoPathList) {
if (videoPathList.size() > 1){
String ffmpegPath = CaptureConfig.getFfmpegPath();
String txtPath = "";
try {
int index = videoPathList.get(0).lastIndexOf(".");
String newMergePath = videoPathList.get(0).substring(0, index) + "new" + videoPathList.get(0).substring(index, videoPathList.get(0).length());
txtPath = videoPathList.get(0).substring(0, index) + ".txt";
FileOutputStream fos = new FileOutputStream(new File(txtPath));
for (String path : videoPathList){
fos.write(("file '" + path + "'\r\n").getBytes());
}
fos.close();
StringBuffer command = new StringBuffer("");
command.append(ffmpegPath);
command.append(" -f");
command.append(" concat");
command.append(" -safe");
command.append(" 0");
command.append(" -i ");
command.append(txtPath);
command.append(" -c");
command.append(" copy ");
command.append(newMergePath);
start(command.toString());
File txtFile = new File(txtPath);
txtFile.delete();
for (String filePath : videoPathList){
File file = new File(filePath);
file.delete();
}
File newFile = new File(newMergePath);
File oldFile = new File(videoPathList.get(0));
newFile.renameTo(oldFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void start(String command){
try {
final Process process = Runtime.getRuntime().exec(command);
LOGGER.info("start run cmd {}", command);
new Thread(){
@Override
public void run (){
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = in.readLine()) != null){
System.out.println("output:" + line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread(){
@Override
public void run (){
BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
try {
while ((line = err.readLine()) != null){
System.out.println("err:" + line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
err.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
process.waitFor();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
测试类
public static void main(String[] args) {
long begin = System.currentTimeMillis();
FileOperateServiceImpl impl = new FileOperateServiceImpl();
List videoPathList = new ArrayList<>();
videoPathList.add("E:\\111.flv");
videoPathList.add("E:\\222.flv");
videoPathList.add("E:\\333.flv");
impl.mergeVideo(videoPathList);
long end = System.currentTimeMillis();
System.out.println(end - begin);
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-17529.html