#!/usr/bin/env python3 """Добавление fade in и fade out к аудиофайлу.""" from __future__ import annotations import argparse import shutil import subprocess import sys from pathlib import Path def duration_of(path: Path, ffprobe: str) -> float: result = subprocess.run( [ ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(path), ], capture_output=True, text=True, check=False, ) try: return float(result.stdout.strip()) except ValueError: return 0.0 def codec_args(suffix: str) -> list[str]: suffix = suffix.lower() if suffix == ".mp3": return ["-c:a", "libmp3lame", "-b:a", "192k"] if suffix == ".m4a": return ["-c:a", "aac", "-b:a", "192k"] if suffix == ".ogg": return ["-c:a", "libvorbis", "-q:a", "5"] if suffix == ".flac": return ["-c:a", "flac"] if suffix == ".wav": return ["-c:a", "pcm_s16le"] return [] def main() -> int: parser = argparse.ArgumentParser(description="Добавить fade in и fade out") parser.add_argument("input", type=Path, help="Исходный файл") parser.add_argument("--fade-in", type=float, default=1.0, help="Длина нарастания в секундах") parser.add_argument("--fade-out", type=float, default=2.0, help="Длина затухания в секундах") parser.add_argument("-o", "--out", type=Path, help="Итоговый файл") parser.add_argument("--overwrite", action="store_true", help="Перезаписать результат") args = parser.parse_args() source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.fade_in < 0 or args.fade_out < 0: parser.error("Длины fade не могут быть отрицательными") if args.fade_in == 0 and args.fade_out == 0: parser.error("Укажите хотя бы один ненулевой fade") ffmpeg = shutil.which("ffmpeg") ffprobe = shutil.which("ffprobe") if not ffmpeg or not ffprobe: print("ffmpeg и ffprobe должны быть установлены.", file=sys.stderr) return 1 total = duration_of(source, ffprobe) if total <= 0: print("Не удалось определить длительность.", file=sys.stderr) return 1 filters: list[str] = [] if args.fade_in > 0: filters.append(f"afade=t=in:st=0:d={min(args.fade_in, total):.3f}") if args.fade_out > 0: fade = min(args.fade_out, total) start = max(0.0, total - fade) filters.append(f"afade=t=out:st={start:.3f}:d={fade:.3f}") destination = args.out.expanduser() if args.out else source.with_name(f"{source.stem}_fade{source.suffix}") destination = destination.resolve() destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists() and not args.overwrite: print(f"Файл уже существует: {destination}", file=sys.stderr) return 1 command = [ ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", str(source), "-af", ",".join(filters), "-map", "0:a", "-map_metadata", "0", ] command += codec_args(destination.suffix) command += ["-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"Ошибка: {result.stderr.strip()}", file=sys.stderr) return 2 print(f"Готово: {destination}") print(f"Fade in: {args.fade_in:.2f} с, fade out: {args.fade_out:.2f} с") return 0 if __name__ == "__main__": raise SystemExit(main())