随笔 - 633,  文章 - 0,  评论 - 13,  阅读 - 48万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

代码

复制代码
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)
复制代码

 

posted on   大话人生  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 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函数定义上传文件路径
点击右上角即可分享
微信分享提示