Ffmpeg合成Mp4:
- 转换格式为ts格式
- 合成Mp4
Ffmpeg命令:
ffmpeg -i 1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts 1.ts
ffmpeg -i 2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts 2.ts
ffmpeg -i 3.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts 3.ts
ffmpeg -i "concat:input1.ts|input2.ts|input3.ts" -c copy -bsf:a aac_adtstoasc -movflags +faststart 4.mp4
Ffmpeg参数解释:
-i 设定输入流
-c copy 拷贝所有流
-bsf:v 比特流过滤器:视频
h264_mp4toannexb 将H.264比特流从长度前缀模式转换为起始码前缀模式(包含H.264流的MP4文件重新转换为mpegts格式)
-f 设定输出格式
Mpegts MPEG2-TS格式的特点就是要求从视频流的任一片段开始都是可以独立解码的
-bsf:a 比特流过滤器:音频
aac:advanced audio coding 高级音频编码
es 基本码流,包含视频、音频或数据的连续码流
ADTS是Audio Data Transport Stream 音频数据传输流
aac_adtstoasc 从MPEG-2/4 ADTS标头创建MPEG-4 AudioSpecificConfig并删除ADTS标头(adts+es+audioSpecificConfig-adts=mp4)
Java部分代码:
public static void convetor(String fromVideoFile) {
List<String> command = new ArrayList<String>();
command.add(ffmpegEXE);
command.add("-y");
command.add("-i");
command.add(fromVideoFile);
command.add("-c");
command.add("copy");
command.add("-bsf:v");
command.add("h264_mp4toannexb");
command.add("-f");
command.add("mpegts");
command.add(fromVideoFile.substring(0,fromVideoFile.lastIndexOf("."))+".ts");
ProcessBuilder builder = new ProcessBuilder(command);
Process process = null;
try {
process = builder.start();
InputStream errorStream = process.getErrorStream();
InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
System.out.println(sb.toString());
if (m.find()) {
int time = getTimelen(m.group(1));
System.out.println(fromVideoFile+",视频时长:"+m.group(1)+", 开始时间:"+m.group(2)+",比特率:"+m.group(3)+"kb/s");
}
if (br != null) {
br.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (errorStream != null) {
errorStream.close();
}
} catch (IOException e) {
System.out.println(fromVideoFile+"--- 视频合并过程出错 ---");
e.printStackTrace();
}
}