Python : How to join multiple video files

I am relatively new to python so bear with me if this is a question that has already been answered before. I am writing a python script to merge several video files together and I have tried to search the answers online but to no avail. I am wondering if I can write a python script without using ffmpeg just pure python codes for the program. I have tried something like this but it doesn't really works

fo=open("outfile","wb")
fo.write(open("infile1").read())
fo.write(open("infile2").read())
fo.close()

I'm not sure, if you can append one video file by the other. Every videofile has a specific format with header, tracks and so on. Take a look at http://en.wikipedia.org/wiki/MPEG_transport_stream. However, with ffmpeg you can do it like this :

ffmpeg -i "concat:input1.mpg|input2.mpg|input3.mpg" -c copy output.mpg

Have a nice day ;)

How to join 10 small videos (~30 sec each), using Python, into 1 , How can I join 10 small videos (~30 sec each), using Python, into 1 video? I need to Get the names of all the files in that folder in a List/Array. How can I create a video with multiple screens of me doing different things? I am relatively new to python so bear with me if this is a question that has already been answered before. I am writing a python script to merge several video files together and I have tried to search the answers online but to no avail. I am wondering if I can write a python script without using ffmpeg just pure python codes for the program.

My use case required concatenating a bunch of .mp3 files spread out over 16 folders into one .mp3 per folder. The documentation at ffmpeg.org and ffmpeg-python was found to be somewhat lacking or confusing...

I was expecting to be able to create an ffmpeg object and then either pass a list or iterate individual path objects into ffmpeg's input, then run concat on the input objects, and then output to a destination, but ffmpeg.input(<FILE LIST>).concat(acodec='copy').output(<OUTFILE>).run() ended up being a massive failball...that is until I came across @CCfVssZijV2X's post containing the concat input formatting which cracked the whole thing for me.

Script below takes base path as input. Assumption is that base path contains folders which contain multiple audio files which are to be concatenated into a single .mp3 per folder as folder name in base path.

If base path contains only one folder, folder batch is sent directly to combine_audio, otherwise the batch list is sent to the multi-processing function which splits each batch over however many cores you have or make available.

While I'm sure the reason for some of my issues with the python wrapper have to do with my ignorance and lack of familiarity with ffmpeg, I hope that this might assist someone or maybe get them started on the correct path for their use case.

from concurrent.futures import ProcessPoolExecutor
from pathlib import Path as p
from os import cpu_count
import ffmpeg

class FFConcat:

    def __init__(self, path, check_files=False):

        self.check_files = check_files
        self.path = p(path)
        self.cores = cpu_count()
        self.batches = []

    def file_check(self):
        '''
        Optional:
        Iterates over folders in path, renames with leading zero for sorting if missing.
        '''
        for folder in sorted(self.path.iterdir()):
            # Folder names were originally "Folder Name - [Disk 1]"
            disk_number = folder.stem.split()[-1].strip(']')
            if len(disk_number) == 1:
                folder.rename('{}/Folder Name - Disk 0{}'.format(self.path, disk_number))
            elif len(disk_number) == 2:
                folder.rename('{}/Folder Name - Disk {}'.format(self.path, disk_number))

    def file_batch(self):
        '''
        Iterates over folders in path creating a list. Converts list into string format
        which is combined with resulting output filename in a dict and added to
        batch list.
        '''
        print('Batching audio files by folder.')
        for folder in sorted(self.path.iterdir()):
            # Use folder names as concat output name for final file.
            outfile = (self.path/'{}.mp3'.format(folder.stem)).as_posix()
            tracks = []
            # Create a list of sorted tracks in folder.
            for track in sorted(folder.iterdir()):
                tracks.append(track.as_posix())
            print('Located {} audio files in \"{}\"'.format(len(tracks), folder.stem))
            # Format file list in string format which ffmpeg will accept via input.
            file_list = '|'.join(_ for _ in tracks)
            # Generate list of dictionaries containing the file list and output filemame
            self.batches.append({
                                'file_list': file_list,
                                'outfile': outfile
                                })

    def combine_audio(self, batch):
        '''
        Input: single dictionary containing a string formatted file list for each folder
        and output filename. Converts list into ffmpeg input concat object. Runs object
        with audio codec copy concatenating files within folder into single file.
        '''
        print('Starting concat for: {}'.format(batch['outfile']))
        tracks = ffmpeg.input('concat:{}'.format(batch['file_list']))
        tracks.output(batch['outfile'], acodec='copy').run()
        print('Completed concat for: {}'.format(batch['outfile']))

    def mp(self, function, iterable):
        '''
        Input: combine_audio function and batch list.
        Sets max workers depending on iterable length and core count.
        '''
        if len(iterable) >= self.cores:
            workers = self.cores
        elif len(iterable) < self.cores:
            workers = len(iterable)
        with ProcessPoolExecutor(max_workers=workers) as p:
            p.map(function, iterable)

    def run(self):

        if self.check_files:
            self.file_check()

        self.file_batch()

        if len(self.batches) == 1:
            print('One batch found. Sending directly to concatenator.')
            self.combine_audio(self.batches[0])
        elif len(self.batches) > 1:
            print('Sending {} batches to multi-processing.'.format(len(self.batches)))
            self.mp(self.combine_audio, self.batches)

concat = FFConcat(path='Base path containing folders with tracks')
concat.run()

MoviePy Tutorial #4: Combine videos, MoviePy is a way to edit videos using python coding. Read about it here: This tutorial shows Duration: 4:06 Posted: Apr 2, 2017 To merge multiple files in a new file, you can simply read files and write them to a new file using loops.For examplefilenames = ['file1.txt', 'file

I am wondering if I can write a python script without using ffmpeg just pure python

No. you will need an understanding of the codec in order to combine the video content (including the audio tracks) and then package it in to the appropriate container. This is not a trivial task which is why there are libraries to automate it.

sverrirs/mp4combine: Automatically concatenates MP4 files , Python script that assist in concatenating mp4 video files into a single larger file and Merging videos containing soft subtitles; Disabling audio in output video. This video merger can merge video files and concatenate various video clips, such as MP4, AVI, FLV, MOV, 3GP, MKV, WMV and more, join and combine multiple video files into one file. Task :Python program to copy one file to another file.

Python script for merging video files (AVI, MP4, MKV) with subtitles , Python script for merging video files (AVI, MP4, MKV) with subtitles (SRT) using ffmpeg (on Windows it will also handle font configuration). To select multiple files, press and hold down CTRL key while clicking on the files one by one. writing the combined data to C. Join (concatenate) video filesIf you have multiple audio or video files encoded with the same codecs, you can join them into a single file using FFmpeg.

Join all Mp4 with Python and Ffmpeg, Join mp4 video with ffmpeg and Python. With the following code you can join all the mp4 in a directory, withou caring of have to input anythong like name of the files or select or other things elenco_file_temp.append(file). Also, Read – Pandas to Combine Multiple CSV Files. A quick wrap up – Merge Multiple CSV Files. In this example, we covered “How to Merge Multiple CSV Files in Python.” It doesn’t use any special Python package to combine the CSV files and can save you a lot of time from going through multiple CSV individually.

Concatenate mp4 videos of different size with Python and ffmpeg , In this code we just use some ffmpeg commands, using Python to look in If you need something very fast to concatenate mp4 video files without the need to modify them, this code is for you. elenco_file_temp.append(file). In this step-by-step tutorial, you'll learn three techniques for combining data in Pandas: merge(), .join(), and concat(). Combining Series and DataFrame objects in Pandas is a powerful way to gain new insights into your data.

Comments
  • Why do you have such an arbitrary restriction?
  • from the question: "I am wondering if I can write a python script _without using ffmpeg_ just pure python codes for the program."
  • +1 for the mp3 files. I wonder if we mp4 or avi files can be concatenated the same way. Do you have any info regarding videos?