#!/usr/bin/env python3 """Извлечение звуковой дорожки из видео.""" from __future__ import annotations import argparse import json import shutil import subprocess from pathlib import Path CODECS = { "mp3": ["-c:a", "libmp3lame", "-b:a", "192k"], "m4a": ["-c:a", "aac", "-b:a", "192k"], "wav": ["-c:a", "pcm_s16le"], "flac": ["-c:a", "flac"], "opus": ["-c:a", "libopus", "-b:a", "128k"], } def audio_streams(path: Path) -> list[dict]: result = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index,codec_name,channels,sample_rate", "-of", "json", str(path), ], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise SystemExit(f"ffprobe не смог прочитать {path}:\n{result.stderr.strip()}") return json.loads(result.stdout).get("streams", []) def main() -> int: parser = argparse.ArgumentParser(description="Извлечь звук из видео") parser.add_argument("input", type=Path) parser.add_argument("--format", choices=tuple(CODECS), default="mp3") parser.add_argument("--output-dir", type=Path, default=Path("audio")) parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() if shutil.which("ffmpeg") is None: raise SystemExit("Не найден ffmpeg. Установите FFmpeg.") source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") streams = audio_streams(source) if not streams: raise SystemExit("В файле нет звуковой дорожки") args.output_dir.mkdir(parents=True, exist_ok=True) target = args.output_dir / f"{source.stem}.{args.format}" if target.exists() and not args.overwrite: raise SystemExit(f"Файл уже существует: {target}. Добавьте --overwrite.") command = [ "ffmpeg", "-hide_banner", "-nostdin", "-i", str(source), "-vn", "-map", "0:a:0", *CODECS[args.format], "-y" if args.overwrite else "-n", str(target), ] print(f"Дорожек найдено: {len(streams)}, извлекается первая") result = subprocess.run(command, check=False) if result.returncode != 0: raise SystemExit(f"ffmpeg завершился с кодом {result.returncode}") print(f"Готово: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())