convert_to_mono.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. from pathlib import Path
  3. from pydub import AudioSegment
  4. from pydub.exceptions import CouldntDecodeError
  5. # --- Configuration ---
  6. input_directory = Path(r"D:\GitHub\Civ14\Resources\Audio\Weapons\Guns\Fire")
  7. # Create a subdirectory for the mono output to avoid overwriting originals initially
  8. output_directory = input_directory / "mono_output"
  9. # --- End Configuration ---
  10. # Ensure the output directory exists
  11. output_directory.mkdir(parents=True, exist_ok=True)
  12. print(f"Input directory: {input_directory}")
  13. print(f"Output directory: {output_directory}")
  14. print("-" * 30)
  15. processed_count = 0
  16. converted_count = 0
  17. skipped_count = 0
  18. error_count = 0
  19. # Iterate through all files in the input directory
  20. for filepath in input_directory.glob("*.ogg"):
  21. processed_count += 1
  22. print(f"Processing: {filepath.name}...")
  23. output_filepath = output_directory / filepath.name
  24. try:
  25. # Load the audio file
  26. audio = AudioSegment.from_ogg(filepath)
  27. # Check if it's already mono
  28. if audio.channels == 1:
  29. print(" Already mono. Skipping conversion (copying file).")
  30. # Optionally copy the original if you want all files in the output dir
  31. # shutil.copy2(filepath, output_filepath)
  32. # For this script, we'll just skip creating a duplicate if it's already mono
  33. skipped_count += 1
  34. continue # Move to the next file
  35. # Convert to mono
  36. print(f" Converting to mono (Channels: {audio.channels} -> 1)...")
  37. mono_audio = audio.set_channels(1)
  38. # Export the mono audio back to Ogg format
  39. # You can add parameters like bitrate if needed: e.g., bitrate="64k"
  40. mono_audio.export(output_filepath, format="ogg")
  41. converted_count += 1
  42. print(f" Saved mono version to: {output_filepath.name}")
  43. except CouldntDecodeError:
  44. print(
  45. f" ERROR: Could not decode file. Is FFmpeg installed and in PATH? Skipping."
  46. )
  47. error_count += 1
  48. except Exception as e:
  49. print(f" ERROR: An unexpected error occurred: {e}")
  50. error_count += 1
  51. print("-" * 30)
  52. print("Batch conversion finished.")
  53. print(f"Total files processed: {processed_count}")
  54. print(f"Files converted: {converted_count}")
  55. print(f"Files skipped (already mono): {skipped_count}")
  56. print(f"Files with errors: {error_count}")
  57. if error_count > 0:
  58. print("\nWARNING: Some files encountered errors. Please check the log above.")
  59. if converted_count > 0 or skipped_count > 0:
  60. print(f"\nMono files (or skipped originals) are in: {output_directory}")