« ◆日本の古曲の音階は第3音を抜いた6音が基本 | トップページ | ◇htmlにテキストブロックコピー機能 »

◇.wavを.mp3に変換するプログラム

 wavをmp3にバッチ的に変換

大量のwavファイルをmp3に変換できるようにバッチプログラムを作成します。

.wavファイルを複数指定することもできる他、ディレクトリを指定することも可能とします。

コマンド形式は次のものとします。

python wav_to_mp3_converter.py
   [-wav      .wavファイル(複数可)]
   [-dir      このディレクトリの.wavファイルを全て対象とする]
   [-dist_dir .mp3ファイルを置くディレクトリ(省略時は.wavと同じ)]
   [-sync     dirとdist_dirで.wavと.mp3を同期させる]
   [-keep     dist_dirの.mp3を保持する]

-syncが指定されている場合,.mp3より.wavが新しい場合、または.mp3が存在しない場合んのみ変換を行います。 -syncが指定され、-keepが指定されていない場合,.wavがない.mp3は消去されます。

プログラムはpythonで作成します。ファイルの変換は次の手続きとなります。

from pydub import AudioSegment
   audio: AudioSegment = AudioSegment.from_wav(wav_file)
   audio.export(mp3_file, format="mp3")

pip install pydubを行っておく必要があります。

プログラム全体を示します。


# wav_to_mp3_converter.py
import os
import argparse
from pydub import AudioSegment
from typing import List, Optional

def convert_wav_to_mp3(wav_file: str, mp3_file: str) -> None:
   """Convert a .wav file to .mp3 format."""
   audio: AudioSegment = AudioSegment.from_wav(wav_file)
   audio.export(mp3_file, format="mp3")
   print(f"Converted: {wav_file} -> {mp3_file}")

def process_files(wav_files: List[str], dst_dir: Optional[str], sync: bool, keep: bool) -> None:
   """Process the provided list of .wav files for conversion."""
   for wav_file in wav_files:
      if not os.path.exists(wav_file) or not wav_file.lower().endswith('.wav'):
         print(f"Skipping invalid or non-existent file: {wav_file}")
         continue

      # If dst_dir is None, use the same directory as the .wav file
      file_dst_dir: str = dst_dir if dst_dir else os.path.dirname(wav_file)
      if not os.path.exists(file_dst_dir):
         os.makedirs(file_dst_dir)

      base_name: str = os.path.basename(wav_file)
      mp3_file: str = os.path.join(file_dst_dir, os.path.splitext(base_name)[0] + ".mp3")
      
      if sync:
         wav_mtime: float = os.path.getmtime(wav_file)
         if os.path.exists(mp3_file):
            mp3_mtime: float = os.path.getmtime(mp3_file)
            if wav_mtime > mp3_mtime:
               convert_wav_to_mp3(wav_file, mp3_file)
         else:
            convert_wav_to_mp3(wav_file, mp3_file)

         if not keep and not os.path.exists(wav_file):
            os.remove(mp3_file)
            print(f"Removed outdated MP3: {mp3_file}")
      else:
         convert_wav_to_mp3(wav_file, mp3_file)

def get_wav_files_from_directory(directory: str) -> List[str]:
   """Get all .wav files from a directory recursively."""
   wav_files: List[str] = []
   for root, _, files in os.walk(directory):
      for file in files:
         if file.lower().endswith('.wav'):
            wav_files.append(os.path.join(root, file))
   return wav_files

def main() -> None:
   parser: argparse.ArgumentParser = argparse.ArgumentParser(description="Convert .wav files to .mp3 format.")
   parser.add_argument("-wav", nargs="*", help="List of .wav files to convert.", default=[])
   parser.add_argument("-dir", help="Directory containing .wav files to convert.")
   parser.add_argument("-dst_dir", help="Destination directory for .mp3 files.", default=None)
   parser.add_argument("-sync", action="store_true", help="Synchronize .wav and .mp3 files.")
   parser.add_argument("-keep", action="store_true", help="Keep .mp3 files even if .wav files are missing.")

   args: argparse.Namespace = parser.parse_args()

   # Collect .wav files
   wav_files: List[str] = args.wav
   if args.dir:
      wav_files.extend(get_wav_files_from_directory(args.dir))
   
   if not wav_files:
      print("No .wav files found for conversion.")
      return

   # Process .wav files
   process_files(wav_files, args.dst_dir, args.sync, args.keep)

if __name__ == "__main__":
   main()
# このプログラムはchatGPTで作成しました

|

« ◆日本の古曲の音階は第3音を抜いた6音が基本 | トップページ | ◇htmlにテキストブロックコピー機能 »