#!/usr/bin/env python3 """Пакетная конвертация аудио в MP3 через ffmpeg.""" from __future__ import annotations import argparse import shutil import subprocess import sys from pathlib import Path AUDIO_EXTENSIONS = { ".wav", ".flac", ".ogg", ".oga", ".aac", ".m4a", ".mp3", ".wma", ".aiff", ".aif", ".opus", } def collect(paths: list[Path], recursive: bool) -> list[tuple[Path, Path]]: result: list[tuple[Path, Path]] = [] for path in paths: if path.is_dir(): iterator = path.rglob("*") if recursive else path.glob("*") for item in iterator: if item.is_file() and item.suffix.lower() in AUDIO_EXTENSIONS: relative = item.relative_to(path).with_suffix(".mp3") result.append((item, relative)) elif path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS: result.append((path, Path(f"{path.stem}.mp3"))) else: print(f"Пропуск: {path} не аудиофайл и не папка", file=sys.stderr) return sorted(result, key=lambda pair: str(pair[0]).lower()) def main() -> int: parser = argparse.ArgumentParser(description="Конвертировать аудио в MP3") parser.add_argument("inputs", nargs="+", type=Path, help="Файлы или папки") parser.add_argument("-o", "--out", type=Path, default=Path("converted"), help="Папка для результата") parser.add_argument("-b", "--bitrate", default="192k", help="Битрейт MP3, например 128k или 320k") parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки") parser.add_argument("--overwrite", action="store_true", help="Перезаписать существующие файлы") args = parser.parse_args() ffmpeg = shutil.which("ffmpeg") if not ffmpeg: print("ffmpeg не найден. Установите FFmpeg и повторите запуск.", file=sys.stderr) return 1 sources = collect([path.expanduser() for path in args.inputs], args.recursive) if not sources: print("Аудиофайлы не найдены.", file=sys.stderr) return 1 out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) done = skipped = failed = 0 for source, relative in sources: destination = out_dir / relative destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists() and not args.overwrite: print(f"Пропуск: {destination} уже существует") skipped += 1 continue command = [ ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", str(source), "-map_metadata", "0", "-codec:a", "libmp3lame", "-b:a", args.bitrate, "-y" if args.overwrite else "-n", str(destination), ] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode == 0: print(f"Готово: {source.name} -> {destination}") done += 1 else: print(f"Ошибка: {source}: {result.stderr.strip()}", file=sys.stderr) failed += 1 print(f"Итог: готово {done}, пропущено {skipped}, ошибок {failed}") return 0 if failed == 0 else 2 if __name__ == "__main__": raise SystemExit(main())