sunnydee123
sunnydee123

Reputation: 11

How to cut videos automatically using Python with FFmpeg?

I'm trying to cut videos automatically using Python with FFmpeg so I don't have to type out the command everytime I want a new video cut. I'm not really sure what I'm doing wrong though, here's the code:

import os

path = r'C:/Users/user/Desktop/folder'

    for filename in os.listdir(path):
       if (filename.endswith(".mp4")): 
           command = "ffmpeg - i" + filename + "-c copy -map 0 -segment_time 00:00:06 -f segment -reset_timestamps 1 output%03d.mp4"
           os.system(command)
       else:
           continue

Upvotes: 0

Views: 5583

Answers (2)

Rango22
Rango22

Reputation: 76

You can cut a video file with ffmpeg.

ffmpeg -i 1.mp4 -vcodec copy -acodec copy -ss 00:03:20 -t 00:10:24 out.mpt

-ss : start_time

-to : end_time

-t : duration_time

Upvotes: 0

Cristiano
Cristiano

Reputation: 267

Typos

First of all, there's a typo in the syntax, as you wrote - i while the correct syntax is -i.
The syntax " + filename + " is correct, however there must be a space before and after

command = "ffmpeg -i " + filename + " -c copy -map 0 -segment_time 00:00:06 -f segment -reset_timestamps 1 output%03d.mp4"

otherwise, you would get an error like

Unrecognized option 'iC:\Users\user\Desktop\folder\filename.mp4-c'.
Error splitting the argument list: Option not found

Solution

I assumed every other argument is correct, for me it didn't work at first, I just had to add
-fflags +discardcorrupt
but maybe it's just my file.

Here's the correct code, however I recommend to you to read this.

Note: I used os.path.join() to save the output file in that same directory because my python file was in another one.

import os

path = r'C:\Users\user\Desktop\folder'

for filename in os.listdir(path):
    if filename.endswith(".mp4"): 
        command = "ffmpeg -fflags +discardcorrupt -i " + os.path.join(path, filename) + " -c copy -map 0 -segment_time 00:00:03 -f segment -reset_timestamps 1 " + os.path.join(path, "output%03d.mp4")
        os.system(command)
    else:
        continue

Upvotes: 2

Related Questions