Search code examples
pythonffmpegyoutubemoviepypytube

ffmpeg_extract_subclip function and moviepy string output error


I have been developing this small application to download and cut Youtube videos. It works fine but an error or misformatted message is the issue I have not fixed. When it comes to the cutting process, the function ffmpeg_extract_subclip is used and right after that point, I get the weird error below: enter image description here

Below, the script working fine. enter image description here

The function responsible for cutting the video

# cutting the video by section
def cut_video(video_local_path, start_time, end_time, final_file):

    print("- Cutting your video...")
    ffmpeg_extract_subclip(video_local_path, time_to_sec(start_time), time_to_sec(end_time), targetname=f"{final_file}.mp4")

If necessary, you can check the full code here on github.

I have extensively read the API for ffmpeg and moviepy, debugged on vscode and checked alternatives like VideoFileClip but it would never give me the same performance.

Thanks in advance.


Solution

  • There are a couple ways to work around this behavior.

    1. Momentarily redirect stdout/stderr

    See this post

    2. Use FFmpeg directly

    moviepy appears to be depending on imageio-ffmpeg for its FFmpeg support, and imageio-ffmpeg gets the FFmpeg path from IMAGEIO_FFMPEG_EXE environmental path downloads FFmpeg executables when the package is installed. So, you should be able to do the following

    
    import imageio_ffmpeg
    import subprocess as sp
    
    ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
    
    sp.run([ffmpeg_path, '-ss', start_time, '-to', end_time, '-i', video_local_path, 
           final_file, '-y'], stderr=sp.NULL, stdout=sp.NULL)
    
    

    Now, if you are using moviepy only for this operation (and other FFmpeg operations), you can drop it altogether and set ffmpeg_path to the FFmpeg path. and just download the FFmpeg binaries via ffmpeg-downloader or static-ffmpeg package. The former is a better choice if you use FFmpeg in multiple venvs (as it saves FFmpeg files in an OS designated user data area, so it only downloads once). The latter is 100% automatic downloading approach similar to imageio-ffmpeg but with no frills.

    [edit: imageio-ffmpeg does not download FFmpeg on its own, so you should already have the FFmpeg executables on your system.]