Конвертировать аудио в OGG Vorbis
Создаёт OGG Vorbis с настраиваемым качеством для совместимости и небольшого размера.
Что делает скрипт
Скрипт кодирует WAV, FLAC, MP3, AAC и M4A в OGG Vorbis через libvorbis. Качество задаётся от 0 до 10, по умолчанию 5. Результаты складываются в отдельную папку, исходники остаются на месте, существующие файлы пропускаются.
Быстрый старт
python convert_to_ogg.py ./music --quality 5
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python convert_to_ogg.py album.flac --quality 7python convert_to_ogg.py ./music --recursive --out ./ogg
Что понадобится
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_ogg.py
#!/usr/bin/env python3
"""Конвертация аудиофайлов в OGG Vorbis."""
from __future__ import annotations
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
SOURCE_EXTENSIONS = {
".wav", ".flac", ".mp3", ".aac", ".m4a", ".wma", ".aiff", ".aif", ".opus",
}
def collect(paths: list[Path], recursive: bool) -> list[Path]:
files: list[Path] = []
for path in paths:
if path.is_dir():
iterator = path.rglob("*") if recursive else path.glob("*")
files.extend(
item for item in iterator
if item.is_file() and item.suffix.lower() in SOURCE_EXTENSIONS
)
elif path.is_file() and path.suffix.lower() in SOURCE_EXTENSIONS:
files.append(path)
else:
print(f"Пропуск: {path}", file=sys.stderr)
return sorted(set(files), key=lambda item: str(item).lower())
def main() -> int:
parser = argparse.ArgumentParser(description="Конвертировать аудио в OGG Vorbis")
parser.add_argument("inputs", nargs="+", type=Path, help="Файлы или папки")
parser.add_argument("-o", "--out", type=Path, default=Path("ogg"), help="Папка для результата")
parser.add_argument("-q", "--quality", type=int, default=5, help="Качество Vorbis от 0 до 10")
parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки")
parser.add_argument("--overwrite", action="store_true", help="Перезаписать существующие файлы")
args = parser.parse_args()
if not 0 <= args.quality <= 10:
parser.error("--quality должен быть от 0 до 10")
ffmpeg = shutil.which("ffmpeg")
if not ffmpeg:
print("ffmpeg не найден. Установите FFmpeg.", file=sys.stderr)
return 1
files = collect([path.expanduser() for path in args.inputs], args.recursive)
if not files:
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 in files:
destination = out_dir / f"{source.stem}.ogg"
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", "libvorbis", "-q:a", str(args.quality),
"-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.name}")
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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.