Python-使用ffprobe获取视频的时长并将视频拆分

时间:2018-10-22 19:22:01

标签: python macos ffmpeg ffprobe

我正在尝试使用ffmpeg分割视频,实现python脚本。

我收到此错误:

Command '['ffprobe', '-i', 'path_to_my_video/MVI_0731.MP4', '-hide_banner']' returned non-zero exit status 1.

这是我用来分割视频的代码:

for video_file in video_files:
        try:
            # Call "ffprobe" to get duration of input video.
            ffprobe_process = subprocess.run(args=["ffprobe", "-i", video_file, "-hide_banner"],
                                           check=True,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           encoding="utf-8",
                                           shell=True)

            # "ffprobe" writes to stderr instead of stdout!
            duration_string = extract_duration_from_ffprobe_output(ffprobe_process.stderr)            
            duration_in_seconds = duration_string_to_seconds(duration_string)

            # Make start_stop_list
            start_stop_list = read_start_stop_list(start_stop_lists[nbr_video])
            nbr_video += 1
            total_pieces = int(len(start_stop_list))

这是引起问题的行:

ffprobe_process = subprocess.run(args=["ffprobe", "-i", video_file, "-hide_banner"],
                                           check=True,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           encoding="utf-8",
                                           shell=True)

当我将其更改为以下代码行:

ffprobe_process = subprocess.run(args=['ffprobe', '-i', video_file, '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")])

有效,我的意思是,脚本在该行之后执行,但是在下一行抛出以下错误:

470.240000
expected string or bytes-like object

470.240000是我的视频的正确播放时间。因此,我对其进行更改的新行效果更好,但仍无法以某种方式使用我的代码。

任何人都知道我该如何解决?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

这是有效的代码:

for video_file in video_files:
        try:
            # Call "ffprobe" to get duration of input video.
            ffprobe_process = subprocess.run(args=["ffprobe", "-i", video_file, '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")])

            # "ffprobe" writes to stderr instead of stdout!
            #duration_string = extract_duration_from_ffprobe_output(ffprobe_process.stderr)     
            duration_string = str(ffprobe_process)   
            #duration_in_seconds = duration_string_to_seconds(duration_string)
            duration_in_seconds = duration_string

            # Make start_stop_list
            start_stop_list = read_start_stop_list(start_stop_lists[nbr_video])
            nbr_video += 1
            total_pieces = int(len(start_stop_list))
            #pdb.set_trace()