ffmpeg java 视频工具类代码,实现拆分合并
时间: 2024-09-06 21:04:07 浏览: 55
基于java实现对长短视频进行片段的裁剪选择+MediaMetadataRetriever获取视频帧+ffmpeg视频裁剪压缩
在Java中使用FFmpeg实现视频的拆分和合并,通常需要借助FFmpeg的命令行工具,并通过Java的ProcessBuilder类来执行这些命令。以下是一个简单的Java工具类示例,展示了如何使用FFmpeg命令进行视频的拆分和合并:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class VideoUtil {
// 执行FFmpeg命令并获取输出
public static String executeCommand(String... cmd) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Command execution failed with exit code " + exitCode + ":\n" + output);
}
return output.toString();
}
// 拆分视频
public static void splitVideo(String inputPath, String outputPath, int startTime, int endTime) {
String[] cmd = {
"ffmpeg",
"-i", inputPath,
"-ss", String.valueOf(startTime),
"-to", String.valueOf(endTime),
"-c", "copy",
outputPath
};
try {
String result = executeCommand(cmd);
System.out.println("Video split result: " + result);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
// 合并视频
public static void mergeVideo(String[] inputFiles, String outputFilePath) {
StringBuilder cmd = new StringBuilder("ffmpeg -f concat -safe 0 -i ");
for (int i = 0; i < inputFiles.length; i++) {
cmd.append(" -i ").append(inputFiles[i]);
}
cmd.append(" -c copy ").append(outputFilePath);
String[] cmdArray = cmd.toString().split(" ");
try {
String result = executeCommand(cmdArray);
System.out.println("Video merge result: " + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用方法:
- 调用`splitVideo`方法来拆分视频,指定输入视频路径、输出视频路径以及拆分的开始时间和结束时间。
- 调用`mergeVideo`方法来合并视频,传入一个包含所有要合并视频文件路径的字符串数组,以及最终输出的视频路径。
示例使用代码:
```java
public class Main {
public static void main(String[] args) {
// 拆分视频示例
VideoUtil.splitVideo("input.mp4", "output.mp4", 0, 10);
// 合并视频示例
String[] videoFiles = {"video1.mp4", "video2.mp4"};
VideoUtil.mergeVideo(videoFiles, "mergedVideo.mp4");
}
}
```
阅读全文