Python code to concat images and ts files using ffmpeg

I have a folder with multiple ts files in it and I want to join the files by inserting an image for n number of duration between videos. Below is the list with the duration for which an image needs to be inserted for.

['00:00:06:17', '00:00:00:16', '00:00:01:05', '00:00:00:31', '00:00:01:01'] For example, if the folder has 5 ts files (this number might change so the folder needs to be iterable) then,

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

Any pointers will be much appreciated.


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()

where new_ts3 is ['00:00:06:17', '00:00:00:16', '00:00:01:05', '00:00:00:31', '00:00:01:01'] and

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

With the above, I am getting 5 files with different filenames but each file is of duration 00:00:06:17

1 answer

  • answered 2019-12-09 12:05 Sushant

    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
    ## finally convert it to mp4 at the last step
    • the flags used in commands are mostly self explanatory such as scale of output.
    • In case of the last loop , we're simply updating the output file name every time by adding that to our file list and combining it with the next item in the list and pushing the output
    • You can convert the final .ts file to any format of your choice. Look for FFMPEG documentation and to execute it in python use the os.system