pythonffmpegsubprocess

How to convert multiple video files in a specific path outputvideo with the same video name


The following code to converts a one video from mp4 to avi using ffmpeg

ffmpeg.exe -i "kingman.mp4" -c copy "kingman.avi"

I need to convert multiple videos in a specific path. "outputvideo" with the same video name

This is the my code that needs to be modified.

from pathlib import Path
import subprocess
from glob import glob

all_files = glob('./video/*.mp4')

for filename in all_files:
     videofile = Path(filename)
     outputfile = Path(r"./outputvideo/")
     codec = "copy"
     ffmpeg_path = (r"ffmpeg.exe")

outputfile = outputfile / f"{videofile.stem}"

outputfile.mkdir(parents=True, exist_ok=True)

command = [
    f"{ffmpeg_path}",
    "-i", f"{videofile}",
    "-c", f"{codec}",
    "{outputfile}",]

process = subprocess.Popen(
    command,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    bufsize=1,
    universal_newlines=True)
process.communicate()

Solution

  • Use ffmpeg.exe if you are using windows, else just ffmpeg will work in case of linux

    from pathlib import Path
    import subprocess
    import os
    from glob import glob
    
    input_folder = "video"
    output_folder = "outputvideo"
    abs_path = os.getcwd()
    all_files = glob(f'{abs_path}/{input_folder}/*.mp4')
    output_dir = os.path.join(abs_path , output_folder)
    out_ext = "avi"
    
    os.makedirs(output_dir , exist_ok=True)
    
    input_dir = os.path.join(abs_path, input_folder)
    
    for filepath in all_files:
        stem = os.path.splitext(os.path.basename(filepath))[0]
        videofile = Path(filepath)
        codec = "copy"
        ffmpeg_path = (r"ffmpeg")
        outputfile = f"{output_dir}/{stem}.{out_ext}"
    
        command = [
            f"{ffmpeg_path}",
            "-i", f"{videofile}",
            "-c", f"{codec}",
            f"{outputfile}",]
    
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1,
            universal_newlines=True)
        stdout, stderr = process.communicate()
    
        # Print output for debugging
        print(f"Processed: {videofile} -> {outputfile}")
        if stderr:
            print(f"FFmpeg Error: {stderr}")