这是一个使用 ffmpeg+MoviePy 库开发的视频切割工具,可以将一个视频文件按照指定时长切割成多个片段。

安装依赖

1
2
3
4
5
brew install python
brew install ffmpeg
cd ./qiege && python3 -m venv venv # 创建虚拟环境,只需创建一次
source venv/bin/activate # 后续运行程序前都需要先激活虚拟环境,然后在虚拟环境中运行你的程序
pip install -r requirements.txt

使用方法

使用命令行运行程序,格式如下:

1
python video_splitter.py 视频路径 [-d 切割时长] [--ignore-duration] [-no-audio] [--output-dir 输出目录]

参数说明:

  • 视频路径:必需参数,指定要切割的视频文件路径
  • -d--duration:可选参数,指定每个片段的时长(秒),默认为10秒
  • --ignore-duration: 可选参数,切割视频时忽略前后30秒
  • --no-audio: 可选参数,去除视频的声音
  • --output-dir: 可选参数,指定输出文件

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 使用默认10秒切割文件夹下的所有视频
python video_splitter.py /path/to/your/video

# 使用默认10秒切割单个视频
python video_splitter.py /path/to/your/video.mp4

# 指定切割时长为15秒
python video_splitter.py /path/to/your/video.mp4 -d 15

# 切割视频时忽略前后30秒
python video_splitter.py /path/to/your/video.mp4  --ignore-duration

注意事项

  • 确保你的系统已安装 Python 3.x
  • 输入视频必须是 MP4 格式
  • 程序会自动在视频目录下创建 result 目录来存放切割后的视频片段
  • 每个视频片段的时长默认为 10 秒,可以通过修改代码中的 segment_duration 参数来调整

代码

  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
import os
import argparse
import hashlib
from datetime import date
import subprocess

def get_video_duration(video_path):
    try:
        # 构建ffprobe命令
        cmd = [
            'ffprobe',
            '-v', 'error',
            '-show_entries', 'format=duration',
            '-of', 'default=noprint_wrappers=1:nokey=1',
            video_path
        ]

        # 执行命令并获取输出
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        # 解析输出结果
        duration = float(result.stdout.strip())
        return duration
    except Exception as e:
        print(f"获取视频时长失败: {str(e)}")
        return None

def calculate_video_md5(file_path):
    """计算视频内容的 MD5 值"""
    md5_hash = hashlib.md5()
    with open(file_path, "rb") as f:
        # 跳过文件头的前1024字节(通常包含元数据)
        f.seek(1024)
        # 读取视频内容
        while True:
            # 每次读取1MB
            chunk = f.read(1024 * 1024)
            if not chunk:
                break
            md5_hash.update(chunk)
    return md5_hash.hexdigest()

def split_video(video_path, duration=10, no_audio=False, output_dir=None, ignore_duration=False):
    try:
        # 检查输入视频是否存在
        if not os.path.exists(video_path):
            print(f"错误:输入视频文件不存在: {video_path}")
            return

        # 创建输出目录
        if output_dir is None:
            # 获取今日日期
            today = date.today()
            date_str = today.strftime("%Y%m%d")

            # 获取视频所在目录并在该目录下创建result文件夹
            video_dir = os.path.dirname(video_path)
            original_output_dir = os.path.join(video_dir, f"result_{date_str}")
            output_dir = original_output_dir

        # 确保输出目录存在
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        print(f"输出目录: {output_dir}")

        # 创建临时目录
        temp_dir = os.path.join(output_dir, "temp")
        if not os.path.exists(temp_dir):
            os.makedirs(temp_dir)

        # 构建 ffmpeg 命令,先输出到临时目录
        cmd = f'ffmpeg -i "{video_path}" -c copy -f segment -segment_time {duration} -reset_timestamps 1'

        # 如果需要去除音频
        if no_audio:
            cmd += f' -an -c:v'

        # 忽略视频的前后30秒
        if ignore_duration:
            total_duration = get_video_duration(video_path)
            cmd += f' -ss 30 -to {total_duration-30}'

        # 添加临时输出路径
        cmd += f' -y "{temp_dir}/temp_%d.mp4"'

        # 执行命令
        print("开始切割视频...")
        os.system(cmd)
        print("视频切割完成!")

        # 重命名文件,使用视频内容的MD5值
        print("正在计算视频内容的MD5值并重命名文件...")
        temp_files = sorted([f for f in os.listdir(temp_dir) if f.startswith("temp_")])
        for temp_file in temp_files:
            temp_file_path = os.path.join(temp_dir, temp_file)
            md5_value = calculate_video_md5(temp_file_path)
            new_name = f"{md5_value}.mp4"
            new_path = os.path.join(output_dir, new_name)
            os.rename(temp_file_path, new_path)
            print(f"已处理: {new_name}")

        # 删除临时目录
        os.rmdir(temp_dir)
        print("所有文件处理完成!")

    except Exception as e:
        print(f"发生错误: {str(e)}")

def process_directory(directory_path, duration=10, no_audio=False, output_dir=None, ignore_duration=False):
    """处理目录中的所有视频文件"""
    try:
        if not os.path.exists(directory_path):
            print(f"错误:目录不存在: {directory_path}")
            return

        # 支持的视频格式
        video_extensions = ('.mp4', '.mov', '.avi', '.mkv', '.MOV', '.MP4', '.AVI', '.MKV')
        # 获取所有视频文件
        video_files = [f for f in os.listdir(directory_path) if f.endswith(video_extensions)]

        if not video_files:
            print("错误:目录中没有找到支持的视频文件")
            return

        print(f"找到 {len(video_files)} 个视频文件:")
        for video_file in video_files:
            print(f"- {video_file}")

        # 创建输出目录
        if output_dir is None:
            # 获取今日日期
            today = date.today()
            date_str = today.strftime("%Y%m%d")

            # 获取视频所在目录并在该目录下创建result文件夹
            video_dir = directory_path
            original_output_dir = os.path.join(video_dir, f"result_{date_str}")
            output_dir = original_output_dir

        # 确保输出目录存在
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        print(f"\n输出目录: {output_dir}")

        # 处理每个视频文件
        for video_file in video_files:
            video_path = os.path.join(directory_path, video_file)
            print(f"\n处理视频: {video_file}")
            split_video(video_path, duration, no_audio, output_dir, ignore_duration)

    except Exception as e:
        print(f"处理目录时发生错误: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="将视频切割成指定时长的片段")
    parser.add_argument("path", help="输入视频文件或文件夹的路径")
    parser.add_argument("--duration", type=int, default=10, help="每个片段的时长(秒),默认为10秒")
    parser.add_argument("--no-audio", action="store_true", help="去除视频的声音")
    parser.add_argument("--output-dir", help="输出目录路径,默认在视频所在目录创建result文件夹")
    parser.add_argument("--ignore-duration", action="store_true", help="切割视频时忽略前后30秒")

    args = parser.parse_args()

    # 判断输入路径是文件还是目录
    if os.path.isfile(args.path):
        split_video(args.path, args.duration, args.no_audio, args.output_dir, args.ignore_duration)
    else:
        process_directory(args.path, args.duration, args.no_audio, args.output_dir, args.ignore_duration)