首页 > 解决方案 > 使用 ffmpeg 连接图像和 ts 文件的 Python 代码

问题描述

我有一个包含多个ts文件的文件夹,我想通过在视频之间插入 n 个持续时间的图像来加入文件。以下是需要插入图像的持续时间列表。

['00:00:06:17', '00:00:00:16', '00:00:01:05', '00:00:00:31', '00:00:01:01'] 例如,如果文件夹有 5 个ts文件(这个数字可能会改变,所以文件夹需要是可迭代的)那么,

video1 + image for 00:00:06:17 + video2 + image for 00:00:00:16 + video 3, etc...

任何指针将不胜感激。

更新:

for i in new_ts3:
    for m in filename[:-1]:
        p1 = subprocess.Popen (['ffmpeg', '-loop', '1', '-i', sys.argv[2], '-c:v', 'libx264', '-profile:v', 'high', '-t', i, '-pix_fmt', 'yuvj420p', '-vf', 'scale=1280:720', '-f', 'mpegts', '{}{}_.ts'.format((os.path.splitext(sys.argv[1]) [0]), m)], stdout=subprocess.PIPE)
        out1 = p1.communicate()
    break

new_ts3在哪里['00:00:06:17', '00:00:00:16', '00:00:01:05', '00:00:00:31', '00:00:01:01']

filename['file1', 'file2', 'file3', 'file4', 'file5', 'file6']

有了以上内容,我得到了 5 个文件名不同的文件,但每个文件都有持续时间00:00:06:17

标签: python-3.xffmpeg

解决方案


import os
i = 0
image_list = ['img1.jpeg', 'img2.jpeg'] 
duration = ['1200', '1300']


## First we make loops of images to videos with given duration
for i in range(len(image_list)):
    # change name according to whatever order you want to save the files format
    outname = image_list[i] + str(i) + '.mp4' 
    dur = duration[i]
    os.system(f'ffmpeg -loop 1 -i {images_list[i]} -c:v libx264 -t {dur} -pix_fmt yuv420p -vf scale=320:240 {outname}')

# Then we onvert .mp4 files to .mpeg if not in .mpeg format as .mp4 files have headers
for file_name in os.listdir(path):
    if (filename.endswith(".mp4")):
        out_name = filename.split(".")[0] + str(.ts)
        os.system(f'ffmpeg -i filename -c copy -bsf:v h264_mp4toannexb -f mpegts {out_name}')

## create a list of the order in which you want to combine files here
order_list = [] # create with your own logic
new_out = 'out.ts'
file_list = os.listdir(path)

for i in range(len(file_list)-1):
    new_out = 'out' + str(i) + '.ts'
    os.system(f'ffmpeg -i "concat:{file_list[i]}|{file_list[i+1]}" -c copy {new_out}')
    if (i+1 < len(file_list))
        file_list[i+1] = new_out
    else: 
        continue

## finally convert it to mp4 at the last step
  • 命令中使用的标志大多是不言自明的,例如输出比例。
  • 在最后一个循环的情况下,我们只是通过将输出文件名添加到我们的文件列表并将其与列表中的下一个项目组合并推送输出来每次更新输出文件名
  • 您可以将最终的 .ts 文件转换为您选择的任何格式。查找 FFMPEG 文档并在 python 中使用 os.system 执行它

推荐阅读