初めに
音声処理をする際にフォルダ内に音声ファイルがあるかを確認したいと思う時があります。その際に使用できる簡単なスクリプトを作ります
環境
- L4 GPU
- ubuntu22.04
準備
必要なライブラリを入れます
sudo apt update sudo apt install ffmpeg pip install pydub
実行
以下で特定のフォルダ内の音声ファイルの合計を計算できるスクリプトを作成します。
import os import sys from pydub import AudioSegment def calculate_total_duration(directory): total_duration = 0 supported_formats = ['wav', 'mp3'] # サポートされるフォーマットをリストに追加 for root, dirs, files in os.walk(directory): for file in files: if any(file.endswith(f".{fmt}") for fmt in supported_formats): audio_path = os.path.join(root, file) try: audio = AudioSegment.from_file(audio_path) total_duration += len(audio) except Exception as e: print(f"ファイル '{file}' を読み込み中にエラーが発生しました: {e}") return total_duration / 1000 # ミリ秒を秒に変換 def format_duration(seconds): hours = seconds // 3600 minutes = (seconds % 3600) // 60 seconds = seconds % 60 return f"{int(hours)}h {int(minutes)}m {int(seconds)}s" if __name__ == "__main__": if len(sys.argv) < 2: print("使用方法: python script.py <音声ファイルが格納されているフォルダのパス>") sys.exit(1) directory_path = sys.argv[1] # コマンドラインからの引数を取得 total_duration_seconds = calculate_total_duration(directory_path) formatted_duration = format_duration(total_duration_seconds) print(f"Total duration: {formatted_duration}")
上記は以下のように使用します
python sum_audio_time.py Data/
結果は以下のように出力されます
Total duration: 7h 53m 4s