代码:
import subprocess from datetime import timedelta import os 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_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) duration = float(result.stdout.decode('utf-8').strip()) return duration def ffmpeg_trim(input_path, output_path, duration): """使用ffmpeg裁剪视频的最后3秒""" # 计算裁剪的结束时间(视频时长 - 3秒) end_time_sec = duration - 3 start_time_sec = 0 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_folder_path = r'E:\edge下载\81' # 遍历文件夹中的所有视频文件 for video_file in os.listdir(video_folder_path): if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')): # 根据需要添加或删除文件类型 # 完整的视频文件路径 video_path = os.path.join(video_folder_path, video_file) # 输出文件路径,这里假设输出文件与原文件同名,但放在不同的文件夹中 output_folder_path = r'E:\edge下载\81_trimmed' if not os.path.exists(output_folder_path): os.makedirs(output_folder_path) output_path = os.path.join(output_folder_path, video_file) # 获取视频的总时长 original_duration = ffmpeg_get_duration(video_path) # 调用函数进行时间裁剪 ffmpeg_trim(video_path, output_path, original_duration) print(f"Trimmed the last 3 seconds of {video_file} successfully.")
标签:裁切,python,三秒,video,time,output,duration,path,folder From: https://www.cnblogs.com/jingzaixin/p/18164318