0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

特定のフォルダ下にある全ての動画ファイル再起的に探索し再生時間を計測する

Last updated at Posted at 2024-11-12

特定のフォルダ下にある全ての動画ファイル再起的に探索し再生時間を計測する

タイトルの通り、そう再生時間を示すことができるやつ。ffmpegが必要。

main.py

import os
import subprocess
from tqdm import tqdm

def get_video_duration_ffprobe(video_path):
    """FFprobeを使用して動画の再生時間を取得(秒単位)"""
    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,
            encoding='utf-8'
        )
        if result.returncode != 0:
            # コマンドが失敗した場合
            print(f"エラーが発生しました: {video_path} - {result.stderr.strip()}")
            return 0
        duration_str = result.stdout.strip()
        try:
            duration = float(duration_str)
        except ValueError:
            print(f"エラーが発生しました: {video_path} - 再生時間の取得に失敗しました")
            return 0
        return duration
    except Exception as e:
        print(f"例外が発生しました: {video_path} - {e}")
        return 0

def get_total_duration(directory):
    total_duration = 0  # 再生時間の合計を秒で保持
    video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv', '.ts')  # 対象とする動画ファイルの拡張子

    # フォルダ内のすべてのファイルを再帰的に探索
    video_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().startswith('h_') and file.lower().endswith(video_extensions):
                video_files.append(os.path.join(root, file))

    # tqdmを使用してプログレスバーを表示
    for video_path in tqdm(video_files, desc="処理進行中", unit="ファイル"):
        total_duration += get_video_duration_ffprobe(video_path)

    return total_duration

# 使用例
directory_path = r"your_file_path"  # 対象のディレクトリパスを指定
total_duration_seconds = get_total_duration(directory_path)

# 時間、分、秒に変換
hours = int(total_duration_seconds // 3600)
minutes = int((total_duration_seconds % 3600) // 60)
seconds = int(total_duration_seconds % 60)


print(f"\n合計再生時間: {hours}時間{minutes}{seconds}")


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?