Пакетная конвертация аудио в MP3
Переводит WAV, FLAC, OGG, AAC и M4A в MP3 с выбранным битрейтом, сохраняя структуру папок.
Что делает скрипт
Скрипт принимает отдельные файлы или каталоги, при обходе папки повторяет вложенную структуру в выходном каталоге. По умолчанию результат складывается в папку converted, существующие файлы не перезаписываются. Теги переносятся через ffmpeg.
Быстрый старт
python convert_to_mp3.py ./music --out ./converted
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python convert_to_mp3.py album.flac --bitrate 320kpython convert_to_mp3.py ./music --recursive --out ./mp3python convert_to_mp3.py song1.wav song2.ogg --overwrite
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
winget install Gyan.FFmpeg
brew install ffmpeg
sudo apt install ffmpeg
convert_to_mp3.py
#!/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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.