FFmpeg 踩坑记录

本菜鸟使用的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(){回调});    //合并视频

有其他解决方法也望大佬指教~

猜你喜欢

转载自blog.csdn.net/qq_38195721/article/details/108519895
今日推荐