本菜鳥使用的FFmpeg封裝工具為 FFmpegCommand 感謝大佬,非常好用,
FFmpegCommand 鏈接:https://github.com/AnJoiner/FFmpegCommand
FFmpeg FAQ :https://ffmpeg.org/faq.html#How-can-I-concatenate-video-files_003f
使用FFmpeg 處理視頻后,得到0kb檔案:
原因:由于專案使用的為 MediaRecorder 錄制視頻,視頻的編碼為H264.而FFmpeg不支持這種視頻編碼,需要轉碼,

ffmepg官方檔案說明:
本人解決方法:
1,將原視頻轉為 .m3u8的視頻流,使用的FFmpegCommand中的 video2HLS()方法
/**
* 將格式視頻進行切片,形成m3u8的視頻流(m3u8格式一般用于直播或者點播)
*
* @param srcFile 視頻路徑
* @param targetFile 目標路徑(以xxx.m3u8為輸出)
* @param splitTime 切割時間 (單位:秒)
* @return 回傳以target檔案名開頭的ts系列檔案 如:out0.ts out1.ts ...
*/
public static String[] video2HLS(String srcFile, String targetFile, int splitTime) {
String command = "ffmpeg -y -i %s -c copy -bsf:v h264_mp4toannexb -hls_time %s %s";
command = String.format(command, srcFile, splitTime, targetFile);
return command.split(" ");
}
2,將生成的.m3u8的視頻流合成視頻,(本菜鳥就直接合成.mp4檔案了)
/**
* 將ts視頻流合成視頻
*
* @param m3u8Index xx.m3u8視頻索引
* @param targetFile 目標路徑
* @return 回傳合成視頻
*/
public static String[] hls2Video(String m3u8Index, String targetFile) {
String command = "ffmpeg -y -i %s -c copy %s";
command = String.format(command, m3u8Index, targetFile);
return command.split(" ");
}
3,再用處理好的視頻檔案進行視頻合成操作,
/**
* 使用ffmpeg命令列進行音視頻合并
*
* @param inputFile 輸入檔案(.txt格式)
* @param targetFile 目標檔案
* @return 合并后的檔案
*/
public static String[] concatVideo(String inputFile, String targetFile) {
// ffmpeg -f concat -i inputs.txt -c copy output.flv
String command = "ffmpeg -y -f concat -i %s -codec copy %s";
command = String.format(command, inputFile, targetFile);
return command.split(" ");//以空格分割為字串陣列
}
本人相關代碼
String videoName = "stitching_child_" + i + ".mp4";
String targetName = "target_child_" + i + ".m3u8";
String targetVideoName = "target_child_" + i + ".mp4";
if (FileUtils.copy2MemoryName(mActivity, info.getPath(), videoName)) {
String childPath = new File(mActivity.getExternalCacheDir(), videoName).getAbsolutePath(); //初始視頻檔案
String targetPath = new File(mActivity.getExternalCacheDir(), targetName).getAbsolutePath(); //合成的m3u8視頻流
FFmpegCommand.runSync(FFmpegUtils.video2HLS(childPath, targetPath, 10)); //將初始檔案轉為m3u8視頻流
String targetVideoPath = new File(mActivity.getExternalCacheDir(), targetVideoName).getAbsolutePath(); //獲取m3u8視頻流路徑
FFmpegCommand.runSync(FFmpegUtils.hls2Video(targetPath, targetVideoPath)); //將m3u8視頻流轉為mp4檔案,
videoPaths.add(FileUtils.getFileName(targetVideoPath)); //添加到需要處理的檔案list里面
FileUtils.deleteCacheFile(mActivity, videoName); //洗掉多余檔案
FileUtils.deleteCacheFile(mActivity, targetName);
}
FFmpegCommand.runAsync(FFmpegUtils.concatVideo(cachePath, targetPath), new CommonCallBack(){回呼}); //合并視頻
有其他解決方法也望大佬指教~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22027.html
標籤:java
下一篇:陣列元素的目標和
