小言_互联网的博客

python截取视频

285人阅读  评论(0)

import os
import math
from glob import glob

VIDEO_DIR = '/media/wywlzyzz/DEE24131E2410EE9/0904/video_raw'
SPAN = 10  # minutes
BIAS = -1  # minutes
OUTPUT_DIR_NAME = 'video_split'

os.chdir(VIDEO_DIR)
os.makedirs(OUTPUT_DIR_NAME)
video_list_MTS = glob('*.MTS')
video_list_mts = glob('*.mts')
video_list = video_list_MTS + video_list_mts
for video_fn in video_list:
    name = video_fn.split('.')[0]
    name_hour_start = int(name[0:2])
    name_minute_start = int(name[2:4])

    process = os.popen("ffmpeg -i {} 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//".format(video_fn))
    video_length = process.read()
    process.close()
    print('video_length:', video_length)

    hour, minute, second = video_length.split(':')
    hour, minute, second = int(hour), int(minute), float(second)
    total_minutes = hour * 60 + minute + second / 60
    hour += name_hour_start
    minute += name_minute_start
    if minute >= 60:
        hour += 1
        minute -= 60

    minutes_processed = 0
    while minutes_processed < total_minutes:

        hour_start = math.floor(minutes_processed / 60)
        minute_start = math.floor(minutes_processed - hour_start * 60)
        second_start = minutes_processed - hour_start * 60 - minute_start

        name_hour_end = name_hour_start
        name_minute_end = name_minute_start + SPAN
        if name_hour_end == hour and name_minute_end > minute:
            name_minute_end = minute + math.ceil(second / 60)
        if name_minute_end >= 60:
            name_hour_end += 1
            name_minute_end -= 60

        command = "ffmpeg -i {} -ss {}:{}:{} -t 00:{}:00 -c copy {}/{}-{}.mp4".format(
            video_fn,
            str(hour_start).zfill(2), str(minute_start).zfill(2), str(second_start).zfill(2),
            str(SPAN).zfill(2),
            OUTPUT_DIR_NAME,
            str(name_hour_start).zfill(2) + str(name_minute_start).zfill(2),
            str(name_hour_end).zfill(2) + str(name_minute_end).zfill(2)
        )
        # print('command:', command)
        p = os.popen(command)
        p.close()
        # command = "ffmpeg -i output/{}-{}.mp4 -c:v libx264 -crf 24 output/{}-{}.flv".format(
        #     str(name_hour_start).zfill(2) + str(name_minute_start).zfill(2),
        #     str(name_hour_end).zfill(2) + str(name_minute_end).zfill(2),
        #     str(name_hour_start).zfill(2) + str(name_minute_start).zfill(2),
        #     str(name_hour_end).zfill(2) + str(name_minute_end).zfill(2)
        # )
        # p = os.popen(command)
        # p.close()

        minutes_processed = minutes_processed + SPAN + BIAS

        name_minute_start = name_minute_start + SPAN + BIAS
        if name_minute_start >= 60:
            name_hour_start = name_hour_start + 1
            name_minute_start = name_minute_start - 60
 


转载:https://blog.csdn.net/weixin_37565521/article/details/101226831
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场