Аудио

Конвертировать аудио в OGG Vorbis

Создаёт OGG Vorbis с настраиваемым качеством для совместимости и небольшого размера.

Python Windows macOS Linux Новичок
Скачать convert_to_ogg.py
Описание

Что делает скрипт

Скрипт кодирует 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 7
  • python convert_to_ogg.py ./music --recursive --out ./ogg
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
FFmpeg 6+ Кодирование, фильтры и ffprobe
Windows winget install Gyan.FFmpeg
macOS brew install ffmpeg
Linux 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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get audio-convert-to-ogg
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Аудио

Конвертация, нормализация, обрезка, теги и подготовка звука.