ffmpeg 文件切片合并

博主在实现m3u8切片合并下载为mp4功能时,考虑使用FFmpeg。介绍了FFmpeg的concat demux和concat protocol两种用法及区别,concat protocol只支持部分视频格式,concat demux只要FFmpeg支持的格式都管用,还通过实验和查阅文档进行了验证。

最近再做m3u8切片合并下载的小功能,因为要合并成mp4,所以考虑用ffmpeg来搞,mp4格式忒复杂了。
查了下文档ffmpeg支持concat demux和concat protocol.
用法如下:
ffmpeg -i “concat:input1.mpg|input2.mpg|input3.mpg” -c copy output.mpg //这个是concat protocal,这个命令只支持一部分视频格式 如mpeg1,2 mpegts,不支持flv,mp4

mylist.txt:

this is a comment

file ‘/path/to/file1’
file ‘/path/to/file2’
file ‘/path/to/file3’

ffmpeg -f concat -i mylist.txt -c copy output //这个是运用concat demux,和前面的命令有些不同,这个会把demux文件然后re-encode切片文件,所以只要ffmpeg支持的格式,这个命令都管用。

开始觉得这俩个命令功能是一样的。实验了第一个命令 flv不管用,只输出了第一片的flv。查了下官方文档找到这一段:

The flv container format doesn’t support file-level concatenation; only a
few container file types do. So the concat protocol won’t work on them.

The concat demuxer, as its name suggests, demuxes the input streams from
their container and then concatenates them, so it doesn’t care about what
the input container is (and if the codecs are all the same w/ similar
characteristics, you can actually concatenate files of different container
formats).

参考:How to concatenate (join, merge) media files
ffmpeg wiki

### 已解密视频切片合并方法 要完成对已解密的 `.ts` 切片文件合并操作,可以借助 `ffmpeg` 这一强大的多媒体处理工具。以下是具体实现方式: #### 使用 Python 调用 FFmpeg 实现 TS 文件合并 通过调用系统的命令行接口运行 FFmpeg 命令,能够高效地将多个 `.ts` 文件按照指定顺序合并成单个 MP4 文件。 ```python import os def merge_ts_files(ts_folder, output_filename="output.mp4"): """ 将指定目录下的 .ts 文件合并为一个 mp4 文件。 参数: ts_folder (str): 存放.ts文件文件夹路径。 output_filename (str): 输出的目标MP4文件名,默认为 'output.mp4'。 """ # 获取所有的TS文件列表并排序 ts_files = sorted([f for f in os.listdir(ts_folder) if f.endswith('.ts')]) # 创建临时文件用于存储FFmpeg输入指令 with open(os.path.join(ts_folder, "filelist.txt"), "w", encoding='utf-8') as filelist: for filename in ts_files: filepath = os.path.abspath(os.path.join(ts_folder, filename)) filelist.write(f"file '{filepath}'\n") # 构建FFmpeg命令 ffmpeg_command = [ "ffmpeg", "-safe", "0", # 避免安全警告 "-f", "concat", "-i", os.path.join(ts_folder, "filelist.txt"), "-c", "copy", output_filename, ] # 执行FFmpeg命令 result = os.system(" ".join(ffmpeg_command)) if result != 0: raise Exception("FFmpeg执行失败,请检查环境配置或参数设置。") # 清理临时文件 os.remove(os.path.join(ts_folder, "filelist.txt")) ``` 上述代码实现了以下功能: 1. **获取所有 `.ts` 文件** 并按名称排序[^2]。 2. **创建临时文件 `filelist.txt`** 来定义 FFmpeg 的输入序列[^1]。 3. **构建 FFmpeg 命令字符串** 并通过 `os.system()` 方法执行该命令。 4. 如果 FFmpeg 成功运行,则删除临时文件;如果失败则抛出异常提示错误信息。 #### 关于 DES 解密后的视频片段 假设每一段 `.ts` 文件都经过了 DES 加密保护,在实际应用中可能还需要额外考虑如下情况: - 密钥管理:确保每个 `.ts` 片段对应的解密密钥已经正确加载。 - 数据完整性校验:某些情况下需要验证解密后的内容是否被篡改过[^3]。 一旦完成了所有 `.ts` 文件的解密工作之后再调用上面提到的函数即可顺利完成最终视频合成过程。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值