Разделить видео на части
Режет ролик на отрезки заданной длины с копированием потоков или перекодированием.
Что делает скрипт
По умолчанию скрипт копирует потоки и делит файл по ключевым кадрам, что работает быстро. С флагом --reencode границы становятся точнее, но обработка занимает больше времени. Части сохраняются в отдельную папку с нумерацией.
- При копировании потоков границы могут сдвигаться к ближайшему ключевому кадру.
Быстрый старт
python split_video.py clip.mp4 --seconds 60
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python split_video.py clip.mp4 --seconds 60python split_video.py lecture.mkv --seconds 300 --reencodepython split_video.py movie.mp4 --seconds 600 --output-dir parts
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
winget install Gyan.FFmpeg
brew install ffmpeg
sudo apt install ffmpeg
split_video.py
#!/usr/bin/env python3
"""Разделение видео на сегменты заданной длины."""
from __future__ import annotations
import argparse
import shutil
import subprocess
from pathlib import Path
def main() -> int:
parser = argparse.ArgumentParser(description="Разделить видео на части")
parser.add_argument("input", type=Path)
parser.add_argument("--seconds", type=int, default=60, help="Длина одной части")
parser.add_argument("--output-dir", type=Path, default=Path("segments"))
parser.add_argument("--reencode", action="store_true", help="Точные границы с перекодированием")
parser.add_argument("--crf", type=int, default=20)
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if shutil.which("ffmpeg") is None:
raise SystemExit("Не найден ffmpeg. Установите FFmpeg.")
source = args.input.expanduser()
if not source.is_file():
parser.error(f"Файл не найден: {source}")
if args.seconds < 1:
parser.error("Длина сегмента должна быть больше нуля")
args.output_dir.mkdir(parents=True, exist_ok=True)
pattern = args.output_dir / f"{source.stem}_%03d.mp4"
existing = sorted(args.output_dir.glob(f"{source.stem}_*.mp4"))
if existing and not args.overwrite:
raise SystemExit(f"В папке уже есть части: {existing[0]}. Добавьте --overwrite.")
command = [
"ffmpeg", "-hide_banner", "-nostdin", "-i", str(source),
"-map", "0:v", "-map", "0:a?", "-f", "segment", "-segment_time", str(args.seconds),
"-reset_timestamps", "1", "-avoid_negative_ts", "make_zero",
]
if args.reencode:
command += [
"-c:v", "libx264", "-preset", "fast", "-crf", str(args.crf),
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",
"-force_key_frames", f"expr:gte(t,n_forced*{args.seconds})",
]
else:
command += ["-c", "copy"]
command += ["-y" if args.overwrite else "-n", str(pattern)]
print(f"Сегменты по {args.seconds} с, перекодирование: {'да' if args.reencode else 'нет'}")
result = subprocess.run(command, check=False)
if result.returncode != 0:
raise SystemExit(f"ffmpeg завершился с кодом {result.returncode}")
parts = sorted(args.output_dir.glob(f"{source.stem}_*.mp4"))
print(f"Готово: {len(parts)} файлов в {args.output_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.