ts 合并成 mp4 请教

291 天前
 wanchenyi

请教哈各位大佬,想做一个下载器放在软路由下载视频,目前视频已经正常下载,但是下载完成是 1500 多个 ts 文件,想要优雅的把它合成 mp4 ,有没有高效,快捷的方式,目前自己尝试的做法是使用 Python 调库,问了 chatgpt ,给出代码``from moviepy.editor import * import os

获取所有 TS 文件

ts_files = [f for f in os.listdir('.') if f.endswith('.ts')] ts_files.sort() # 如果需要按特定顺序排序

每批合并的视频数量

batch_size = 50

临时合并的视频列表

temp_videos = []

分批合并视频

for i in range(0, len(ts_files), batch_size): batch_files = ts_files[i:i + batch_size] clips = [VideoFileClip(f) for f in batch_files] video = concatenate_videoclips(clips) temp_file = f"temp_{i}.mp4" video.write_videofile(temp_file) temp_videos.append(temp_file)

合并临时视频

final_clips = [VideoFileClip(f) for f in temp_videos] final_video = concatenate_videoclips(final_clips) final_video.write_videofile("final.mp4")

删除临时视频文件

for f in temp_videos: os.remove(f)

这是调整后代码,之前给出的代码。第一版给出的代码如下

from moviepy.editor import VideoFileClip, concatenate_videoclips import os import gc

Define a list of video file paths

ts_files = [ 'video1.ts', 'video2.ts', 'video3.ts', # Add more file paths ]

Create a temporary directory to store intermediate MP4 files

temp_dir = "temp_mp4_files" os.makedirs(temp_dir, exist_ok=True)

Convert each TS file to MP4

mp4_files = [] for ts_file in ts_files: clip = VideoFileClip(ts_file) mp4_file_path = os.path.join(temp_dir, os.path.basename(ts_file).replace(".ts", ".mp4")) clip.write_videofile(mp4_file_path, codec="libx264", fps=24) clip.close() mp4_files.append(mp4_file_path) # Force a garbage collection to free up memory gc.collect()

Load the MP4 clips

clips = [VideoFileClip(mp4_file) for mp4_file in mp4_files]

Concatenate the clips

final_video = concatenate_videoclips(clips, method="compose")

Save the concatenated video to an MP4 file

final_video.write_videofile("output.mp4", codec="libx264", fps=24)

Close the clips and delete temporary files

for clip in clips: clip.close() for mp4_file in mp4_files: os.remove(mp4_file) os.rmdir(temp_dir) gc.collect()

这个代码好像因为打开的文件太多了报错了。
去搜了哈 ffmpeg 的教程,搜到的是,先创建一个 文件夹,把所有 ts 的路径按顺序写入一个 文件 ,然后 再执行命令`ffmpeg.exe -f concat -safe 0 -i file.txt -c copy out.mp4`就 OK 了(这个方法目前还没有尝试)。
717 次点击
所在节点    问与答
5 条回复
6IbA2bj5ip3tK49j
291 天前
ffmpeg 最简单

ffmpeg -f concat -i list.txt -acodec copy -vcodec copy output.mp4

list.txt 里面按照如下写入
file 1.ts
file 2.ts
file 3.ts
file 4.ts
LLaMA2
291 天前
ffmpeg -i "http://host/folder/file.m3u8" -bsf:a aac_adtstoasc -vcodec copy -c copy -crf 50 file.mp4
poporange
291 天前
ffmpeg
xiangyuecn
291 天前
有没有一种可能:直接把所有普通冒加密的 ts 拼接起来,就能得到一个完整 ts ,压根不需要转码😂
wanchenyi
291 天前
@xiangyuecn 我看油猴里那个下载 m3u8 的视频,好像就是这样搞的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/961123

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX