Combine videos with python

Asked 2 years ago, Updated 2 years ago, 90 views

Objective: I want to combine multiple mp4 videos with python.The video and sound are the same.

The original movie is located in the movies_in folder in the same hierarchy as the executable.
Comb_movie() combines the original audio video and outputs it without audio.
In set_audio(), the sound extracted from the original video is combined and attached to the video I just printed.

Full Code:

import cv2
import glob
import moviepy.editor asmp
from pydub import AudioSegment

# File Name
input_folder="movies_in"# folder with videos to load
sound_out="sound_out.mp3"#audio-only output
movie_out="movie_out.mp4"# Video and audio output

# Combine the original video and output it without sound
defcomb_movie(movies_in, image_out):

    # Format is mp4
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')

    # acquisition of video information
    movie=cv2.VideoCapture(movies_in[0])
    fps=movie.get(cv2.CAP_PROP_FPS)
    height=movie.get(cv2.CAP_PROP_FRAME_HEIGHT)
    width=movie.get(cv2.CAP_PROP_FRAME_WIDTH)


    # open the output destination file
    out = cv2.VideoWriter(image_out, int(fourcc), fps, (int(width), int(height)))

    for movie_in in movies_in:
        # Video file read, arguments are the path of video file paths
        movie=cv2.VideoCapture(movie_in)

        # Verify That the Video File Was Loaded Successfully
        if movie.isOpened() == True: 
            # read() —Reads capture image data for one frame
            ret,frame=movie.read()
        else:
            ret = False
            print(movie_in+": Failed to load")

        while ret:
            # Write the frame you read
            out.write(frame)
            # Read Next Frame
            ret,frame=movie.read()


# Combine the sound of the original video and add it to the video only.
default_audio(movies_in, movie_out, sound_out):

    clip=mp.VideoFileClip(movie_out).subclip()

    sound=None

    # Extract and combine audio from the original file one by one
    for movie_in in movies_in:
        sound+=AudioSegment.from_file(movie_in)

    # Output combined audio
    sound.export(sound_out, format="mp3")

    # Add combined audio to video
    clip.write_videofile(movie_out, audio=sound_out)


# Sort mp4 files in folders by name
movies_in=sorted(glob.glob(input_folder+"\*.mp4"))

comb_movie(movies_in, movie_out)

set_audio(movies_in, movie_out, sound_out)

print ("Finish")

The line with the error is sound+=AudioSegment.from_file(movie_in) in set_audio().
The variable sound is added one voice at a time from the original file.

The following error appears:

Traceback (most recent call last):
  File "C:\Users\OneDrive\Desktop\Video Test\Video Test.py", line 69, in<module>
    set_audio(movies_in, movie_out, sound_out)
  File "C:\Users\OneDrive\Desktop\Video Test\Video Test.py", line 55, in set_audio
    sound+=AudioSegment.from_file(movie_in)
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\pydub\audio_segment.py", line 728, in from_file
    info=mediainfo_json(orig_file, read_ahead_limit=read_ahead_limit)
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\pydub\utils.py", line 274, in mediainfo_json
    res=Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE)
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line1420, in_execute_child
    hp,ht,pid,tid=_winapi.CreateProcess(executable,args,
FileNotFoundError: [WinError2] The specified file cannot be found.

Actually, the original video is in the movies_in folder.
Is the method of specifying the file specification?
Please tell me how to fix it.

When I wrote the code, I referred to the following pages.

Video Combination:
https://qiita.com/okamoto441/items/3ada3cad3b6210ca8150

Add audio to video:
https://kp-ft.com/684

Voice-to-voice combination:
https://algorithm.joho.info/programming/python/pydub-connection/

python python3 opencv video

2022-09-30 10:29

1 Answers

Jackson's answer solved the problem for now, so I'll show you how to do it.
It seems that there is still a problem with the sound shift after a long time of the video.

Changes
·Install ffmpeg and pass through the path
·Output video only once, and output video with sound as a separate file

Full Code:

import cv2
import glob
import moviepy.editor asmp
from pydub import AudioSegment
import numpy

# File Name
input_folder="movies_in"# folder with videos to load
image_out="image_out.mp4"#Output video only
sound_out="sound_out.mp3"#audio-only output
movie_out="movie_out.mp4"# Video and audio output

# Combine the original video and output it without sound
defcomb_movie(movies_in, image_out):

    # Format is mp4
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')

    # acquisition of video information
    movie=cv2.VideoCapture(movies_in[0])
    fps=movie.get(cv2.CAP_PROP_FPS)
    height=movie.get(cv2.CAP_PROP_FRAME_HEIGHT)
    width=movie.get(cv2.CAP_PROP_FRAME_WIDTH)


    # open the output destination file
    out = cv2.VideoWriter(image_out, int(fourcc), fps, (int(width), int(height)))

    for movie_in in movies_in:
        # Video file read, arguments are the path of video file paths
        movie=cv2.VideoCapture(movie_in)

        # Verify That the Video File Was Loaded Successfully
        if movie.isOpened() == True: 
            # read() —Reads capture image data for one frame
            ret,frame=movie.read()
        else:
            ret = False
            print(movie_in+": Failed to load")
            
        while ret:
            # Write the frame you read
            out.write(frame)
            # Read Next Frame
            ret,frame=movie.read()

        print(movie_in)

# Combine the sound of the original video and add it to the video only.
default_audio(movies_in, movie_out, image_out, sound_out):

    sound=None

    # Extract and combine audio from the original file one by one
    for movie_in in movies_in:
        if sound==None:
            sound=AudioSegment.from_file(movie_in, "mp4")
        else:
            sound+=AudioSegment.from_file(movie_in, "mp4")
            
    # Output combined audio
    sound.export(sound_out, format="mp3")
    
    clip=mp.VideoFileClip(image_out).subclip()
    
    # Add combined audio to video
    clip.write_videofile(movie_out, audio=sound_out)


# Sort mp4 files in folders by name
movies_in=sorted(glob.glob(input_folder+"\*.mp4"))

comb_movie(movies_in, image_out)

set_audio(movies_in, movie_out, image_out, sound_out)

print ("Finish")

I used this as a reference for installing ffmpeg and passing through the path.
Easy way to create animation GIFs and videos in Python

How do I install FFmpeg on Windows 10 and add FFmpeg to my Windows path


2022-09-30 10:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.