代码
import subprocess from datetime import timedelta def parse_time(time_str): """将时间字符串解析为秒""" # 将时间字符串分割为小时、分钟和秒 hours, minutes, seconds = map(int, time_str.split(':')) # 计算总秒数 return timedelta(hours=hours, minutes=minutes, seconds=seconds).total_seconds() def ffmpeg_trim(input_path, output_path, start_time, end_time): # 将时间字符串转换为秒 start_time_sec = parse_time(start_time) end_time_sec = parse_time(end_time) # 构建ffmpeg命令 cmd = [ 'ffmpeg', '-i', input_path, # 输入文件 '-ss', str(start_time_sec), # 开始时间 '-to', str(end_time_sec), # 结束时间 '-c', 'copy', # 复制编解码器设置,避免重新编码 output_path # 输出文件 ] # 执行ffmpeg命令 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下载\80-\80-难度等级_keyong.mp4' # 裁剪后的视频文件路径 output_path = r'E:\edge下载\80-\80-难度等级_qutou.mp4' # 开始时间(HH:MM:SS格式) start_time = '00:00:08' # 视频的第8秒开始 # 结束时间(HH:MM:SS格式) end_time = '00:03:38' # 视频的第3分37秒结束 # 调用函数进行时间裁剪 ffmpeg_trim(video_path, output_path, start_time, end_time)
指定目录下所有文件,代码:
import subprocess import os import re 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}") def is_video_file(file_path): """检查文件是否为视频文件""" video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv') return any(file_path.lower().endswith(ext) for ext in video_extensions) def trim_videos_in_directory(directory_path): """遍历指定目录下的所有视频文件,并进行裁剪""" for root, dirs, files in os.walk(directory_path): for file in files: file_path = os.path.join(root, file) if is_video_file(file_path): print(f"Processing video: {file_path}") # 获取视频的总时长 original_duration = ffmpeg_get_duration(file_path) # 打印视频的总时长(HH:MM:SS格式) print(f"Original video duration: {str(timedelta(seconds=original_duration))}") # 用户定义的裁剪开始时间 start_time_defined = '00:00:13' # 从第13秒开始裁剪 # 计算裁剪的结束时间(原视频时长 + 1秒) end_time_defined = str(timedelta(seconds=original_duration + 1)) # 构建输出文件路径 output_path = os.path.splitext(file_path)[0] + "-qutou.mp4" # 调用函数进行时间裁剪 ffmpeg_trim(file_path, output_path, start_time_defined, end_time_defined) print(f"Trimmed video saved to: {output_path}") # 指定的目录路径 directory_path = r"D:\caiqie" trim_videos_in_directory(directory_path)
可以指定开始时间和结束时间的,代码:
import subprocess import os import re 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.decode().strip()) 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}") def is_video_file(file_path): """检查文件是否为视频文件""" video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv') return any(file_path.lower().endswith(ext) for ext in video_extensions) def trim_videos_in_directory(directory_path, start_time, end_time): """遍历指定目录下的所有视频文件,并进行裁剪""" for root, dirs, files in os.walk(directory_path): for file in files: file_path = os.path.join(root, file) if is_video_file(file_path): print(f"Processing video: {file_path}") # 获取视频的总时长 original_duration = ffmpeg_get_duration(file_path) # 打印视频的总时长(HH:MM:SS格式) print(f"Original video duration: {str(timedelta(seconds=original_duration))}") # 构建输出文件路径 output_path = os.path.splitext(file_path)[0] + "-trimmed.mp4" # 调用函数进行时间裁剪 ffmpeg_trim(file_path, output_path, start_time, end_time) print(f"Trimmed video saved to: {output_path}") # 指定的目录路径 directory_path = r"D:\caiqie" # 用户定义的裁剪开始时间和结束时间 start_time_defined = '00:00:13' # 从第13秒开始裁剪 end_time_defined = '00:00:20' # 裁剪到第20秒 trim_videos_in_directory(directory_path, start_time_defined, end_time_defined)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2022-04-20 给图片添加文字
2022-04-20 ubuntu命令启动django
2022-04-20 ubuntu18.04配置网络
2020-04-20 django部署
2020-04-20 django函数定义上传文件路径