Movatterモバイル変換


[0]ホーム

URL:


How to Concatenate Video Files in Python

Learn how to join two or more video files using MoviePy library in Python
  · 4 min read · Updated may 2024 ·Python for Multimedia

Kickstart your coding journey with ourPython Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!

In this tutorial, you will learn how to join two or more video files together using Python with the help of theMoviePy library.

This tutorial is similar to thejoining audio files tutorial, but we'll join videos in this one.

To get started, let's install MoviePy first:

$ pip install moviepy

MoviePy usesFFmpeg software under the hood and will install it once you execute the MoviePy code the first time. Open up a new Python file and write the following code:

def concatenate(video_clip_paths, output_path, method="compose"):    """Concatenates several video files into one video file    and save it to `output_path`. Note that extension (mp4, etc.) must be added to `output_path`    `method` can be either 'compose' or 'reduce':        `reduce`: Reduce the quality of the video to the lowest quality on the list of `video_clip_paths`.        `compose`: type help(concatenate_videoclips) for the info"""    # create VideoFileClip object for each video file    clips = [VideoFileClip(c) for c in video_clip_paths]    if method == "reduce":        # calculate minimum width & height across all clips        min_height = min([c.h for c in clips])        min_width = min([c.w for c in clips])        # resize the videos to the minimum        clips = [c.resize(newsize=(min_width, min_height)) for c in clips]        # concatenate the final video        final_clip = concatenate_videoclips(clips)    elif method == "compose":        # concatenate the final video with the compose method provided by moviepy        final_clip = concatenate_videoclips(clips, method="compose")    # write the output video file    final_clip.write_videofile(output_path)

Okay, there is a lot to cover here. Theconcatenate() function we wrote accepts the list of video files (video_clip_paths), the output video file path, and the method of joining.

First, we loop over the list of video files and load them usingVideoFileClip() object from MoviePy. The method parameter accepts two possible values:

  • reduce: This method reduces the video quality to the lowest on the list. For instance, if one video is1280x720 and the other is320x240, the resulting file will be320x240. That's why we use theresize() method to the lowest height and width.
  • compose: MoviePy advises us to use this method when the concatenation is done on videos with different qualities. The final clip has the height of the highest clip and the width of the widest clip of the list. All the clips with smaller dimensions will appear centered.

Feel free to use both and see which one fits your case best.

Now, let's use theargparse module to parse command-line arguments:

if __name__ == "__main__":    import argparse    parser = argparse.ArgumentParser(        description="Simple Video Concatenation script in Python with MoviePy Library")    parser.add_argument("-c", "--clips", nargs="+",                        help="List of audio or video clip paths")    parser.add_argument("-r", "--reduce", action="store_true",                         help="Whether to use the `reduce` method to reduce to the lowest quality on the resulting clip")    parser.add_argument("-o", "--output", help="Output file name")    args = parser.parse_args()    clips = args.clips    output_path = args.output    reduce = args.reduce    method = "reduce" if reduce else "compose"    concatenate(clips, output_path, method)

Since we're expecting a list of video files to be joined together, we need to pass"+" tonargs for the parser to accept one or more video files.

Let's pass--help:

$ python concatenate_video.py --help

Output:

usage: concatenate_video.py [-h] [-c CLIPS [CLIPS ...]] [-r REDUCE] [-o OUTPUT]Simple Video Concatenation script in Python with MoviePy Libraryoptional arguments:  -h, --help            show this help message and exit  -c CLIPS [CLIPS ...], --clips CLIPS [CLIPS ...]                        List of audio or video clip paths  -r REDUCE, --reduce REDUCE                        Whether to use the `reduce` method to reduce to the lowest quality on the resulting clip  -o OUTPUT, --output OUTPUT                        Output file name

Let's test it out:

$ python concatenate_video.py -c zoo.mp4 directed-by-robert.mp4 -o output.mp4

Here I'm joiningzoo.mp4 withdirected-by-robert.mp4 files to produceoutput.mp4. Note that the order is important, so you need to pass them in the order you want. You can pass as many video files as you want. Theoutput.mp4 will appear in the current directory, and you'll see a similar output to this:

Moviepy - Building video output.mp4.MoviePy - Writing audio in outputTEMP_MPY_wvf_snd.mp3MoviePy - Done.Moviepy - Writing video output.mp4Moviepy - Done !Moviepy - video ready output.mp4

And this is the output video:

You can also use thereduce method with the following command:

$ python concatenate_video.py -c zoo.mp4 directed-by-robert.mp4 --reduce -o output-reduced.mp4

Alright, there you go. I hope this tutorial helped you out on your programming journey!

Learn also:How to Combine a Static Image with Audio in Python

Happy coding ♥

Found the article interesting? You'll love ourPython Code Generator! Give AI a chance to do the heavy lifting for you. Check it out!

View Full Code Auto-Generate My Code
Sharing is caring!



Read Also


How to Combine a Static Image with Audio in Python
How to Extract Audio from Video in Python
How to Play and Record Audio in Python

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Practical Python PDF Processing EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Practical Python PDF Processing EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Practical Python PDF Processing Chapter.

    See how the book can help you build handy PDF Processing tools!



    [8]ページ先頭

    ©2009-2025 Movatter.jp