#!/usr/bin/env python3 """Обрезка аудиофайла по времени.""" from __future__ import annotations import argparse import shutil import subprocess import sys from pathlib import Path def parse_time(value: str) -> float: parts = value.strip().split(":") try: if len(parts) == 1: return float(parts[0]) if len(parts) == 2: return int(parts[0]) * 60 + float(parts[1]) if len(parts) == 3: return int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2]) except ValueError as error: raise argparse.ArgumentTypeError(f"Неверное время: {value}") from error raise argparse.ArgumentTypeError(f"Неверное время: {value}") 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="Обрезать аудиофайл") parser.add_argument("input", type=Path, help="Исходный файл") parser.add_argument("--start", type=parse_time, default=0.0, help="Начало, например 0:30") parser.add_argument("--end", type=parse_time, help="Конец, например 1:15") parser.add_argument("--duration", type=parse_time, help="Длительность фрагмента") parser.add_argument("-o", "--out", type=Path, help="Итоговый файл") parser.add_argument("--copy", action="store_true", 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.end is not None and args.duration is not None: parser.error("Укажите что-то одно: --end или --duration") if args.start < 0: parser.error("--start не может быть отрицательным") if args.end is not None and args.end <= args.start: parser.error("--end должен быть больше --start") if args.duration is not None and args.duration <= 0: parser.error("--duration должен быть больше нуля") 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 if args.start >= total: parser.error("Начало позже конца файла") end = args.end if end is None: length = args.duration if args.duration is not None else max(0.0, total - args.start) else: length = end - args.start if total > 0 and args.start + length > total: length = max(0.0, total - args.start) print("Конец за пределами файла, длина уменьшена.", file=sys.stderr) destination = args.out.expanduser() if args.out else source.with_name(f"{source.stem}_trim{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 if args.copy: command = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-ss", f"{args.start:.3f}"] command += ["-i", str(source), "-t", f"{length:.3f}", "-map", "0:a", "-c", "copy"] command += ["-map_metadata", "0", "-avoid_negative_ts", "make_zero"] else: command = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", str(source)] command += ["-ss", f"{args.start:.3f}", "-t", f"{length:.3f}"] command += ["-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"Начало: {args.start:.2f} с, длина: {length:.2f} с") return 0 if __name__ == "__main__": raise SystemExit(main())