代码:
import subprocess from datetime import timedelta def parse_time(time_str): """将时间字符串解析为秒""" # 如果输入是浮点数,直接返回这个数值 if isinstance(time_str, float): return time_str # 将时间字符串分割为小时、分钟和秒 hours, minutes, seconds = map(float, time_str.split(':')) # 计算总秒数 return timedelta(hours=hours, minutes=minutes, seconds=seconds).total_seconds() def ffmpeg_get_duration(input_path): """获取视频的总时长(秒)""" result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 将ffprobe输出的时长字符串转换为浮点数 duration = float(result.stdout) return duration # 其他函数保持不变... def ffmpeg_trim(input_path, output_path, start_time, end_time): """使用ffmpeg裁剪视频""" start_time_sec = parse_time(start_time) end_time_sec = parse_time(end_time) cmd = [ 'ffmpeg', '-i', input_path, '-ss', str(start_time_sec), '-to', str(end_time_sec), '-c', 'copy', output_path ] try: subprocess.run(cmd, check=True) except subprocess.CalledProcessError as e: print(f"An error occurred while processing the video: {e}") # 要裁剪的视频文件路径 video_path = r'E:\edge下载\81\81-创建渲染框架.mp4' output_path = r'E:\edge下载\81\81-创建渲染框架_qutou.mp4' # 获取视频的总时长 original_duration = ffmpeg_get_duration(video_path) # 打印视频的总时长(HH:MM:SS格式) print(f"Original video duration: {str(timedelta(seconds=original_duration))}") # 用户定义的裁剪开始时间 start_time_defined = '00:00:08' # 从第08秒开始裁剪 # 计算裁剪的结束时间(原视频时长 + 1秒) end_time_defined = str(timedelta(seconds=original_duration + 1)) # 调用函数进行时间裁剪 ffmpeg_trim(video_path, output_path, start_time_defined, end_time_defined)
标签:裁切,seconds,截取,subprocess,时间,str,time,duration,path From: https://www.cnblogs.com/jingzaixin/p/18148204