Skip to content

Instantly share code, notes, and snippets.

@m-szk
Last active April 24, 2025 08:58
Show Gist options
  • Save m-szk/afd94e5ba87015d1a9b1efe3a46930d6 to your computer and use it in GitHub Desktop.
Save m-szk/afd94e5ba87015d1a9b1efe3a46930d6 to your computer and use it in GitHub Desktop.
Cut out video at regular intervals.
import argparse
import os
import sys
import subprocess
# 定数
SUPPORTED_EXTENSIONS = (".mp4", ".mov")
def get_video_duration(video_path):
"""動画の長さを取得"""
try:
result = subprocess.run(
['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', video_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
return float(result.stdout)
except subprocess.CalledProcessError as e:
print(f"Error getting video duration: {e}")
sys.exit(1)
return 0
def parse_arguments():
"""コマンドライン引数を解析"""
parser = argparse.ArgumentParser(description='Video cut')
parser.add_argument('video_path', help='Video file path')
parser.add_argument('time', type=float, help='Cutout time (sec)')
parser.add_argument('step', type=float, help='Cutout interval (sec)')
parser.add_argument('-o', '--output_dir', help='Output directory', default='.')
return parser.parse_args()
def validate_output_directory(output_dir):
"""出力ディレクトリの存在を確認"""
if not os.path.isdir(output_dir):
print(f"Output directory does not exist: {output_dir}")
sys.exit(1)
def generate_output_filename(video_path, output_dir, start):
"""出力ファイル名を生成"""
base_name, ext = os.path.splitext(os.path.basename(video_path))
return os.path.join(output_dir, f"{base_name}_{int(start)}{ext}")
def cut_video(video_path, duration, time, step, output_dir):
"""動画を指定した間隔でカット"""
start = 0
while start < duration:
out_file = generate_output_filename(video_path, output_dir, start)
try:
subprocess.run(
['ffmpeg', '-i', video_path, '-ss', str(start), '-t', str(time), '-c', 'copy', out_file],
check=True
)
print(f"Created: {out_file}")
except subprocess.CalledProcessError as e:
print(f"Error cutting video at {start} seconds: {e}")
start += step
def main():
args = parse_arguments()
validate_output_directory(args.output_dir)
duration = get_video_duration(args.video_path)
cut_video(args.video_path, duration, args.time, args.step, args.output_dir)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment