#!/usr/bin/env python3 """Разбиение аудио на фрагменты по тишине.""" from __future__ import annotations import argparse import re import shutil import subprocess import sys from pathlib import Path START_RE = re.compile(r"silence_start:\s*(-?\d+(?:\.\d+)?)") END_RE = re.compile(r"silence_end:\s*(-?\d+(?:\.\d+)?)") def probe_duration(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 detect_silences(path: Path, ffmpeg: str, threshold: str, minimum: float) -> list[tuple[float, float]]: command = [ ffmpeg, "-hide_banner", "-nostdin", "-i", str(path), "-af", f"silencedetect=noise={threshold}:d={minimum}", "-f", "null", "-", ] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode != 0: raise RuntimeError(result.stderr.strip()) starts = [float(value) for value in START_RE.findall(result.stderr)] ends = [float(value) for value in END_RE.findall(result.stderr)] silences: list[tuple[float, float]] = [] for index, start in enumerate(starts): if index < len(ends) and ends[index] > start: silences.append((max(0.0, start), ends[index])) return silences def codec_args(fmt: str) -> list[str]: if fmt == "wav": return ["-c:a", "pcm_s16le"] if fmt == "flac": return ["-c:a", "flac"] return ["-c:a", "libmp3lame", "-b:a", "192k"] def main() -> int: parser = argparse.ArgumentParser(description="Разбить аудио по тишине") parser.add_argument("input", type=Path, help="Исходный аудиофайл") parser.add_argument("-o", "--out", type=Path, default=Path("parts"), help="Папка для фрагментов") parser.add_argument("--threshold", default="-40dB", help="Порог тишины, например -40dB") parser.add_argument("--min-silence", type=float, default=0.7, help="Минимальная длина паузы в секундах") parser.add_argument("--min-segment", type=float, default=2.0, help="Минимальная длина фрагмента") parser.add_argument("--prefix", default=None, help="Префикс имён файлов") parser.add_argument("--format", choices=["mp3", "wav", "flac"], default="mp3", help="Формат фрагментов") parser.add_argument("--overwrite", action="store_true", help="Перезаписать существующие файлы") raw = sys.argv[1:] fixed: list[str] = [] skip = False for index, value in enumerate(raw): if skip: skip = False continue if value == "--threshold" and index + 1 < len(raw): candidate = raw[index + 1] if candidate.startswith("-") and candidate not in ("-h", "--help"): fixed.append(f"--threshold={candidate}") skip = True continue fixed.append(value) args = parser.parse_args(fixed) source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.min_silence <= 0 or args.min_segment <= 0: parser.error("Длины должны быть больше нуля") ffmpeg = shutil.which("ffmpeg") ffprobe = shutil.which("ffprobe") if not ffmpeg or not ffprobe: print("ffmpeg и ffprobe должны быть установлены.", file=sys.stderr) return 1 total = probe_duration(source, ffprobe) if total <= 0: print("Не удалось определить длительность файла.", file=sys.stderr) return 1 try: silences = detect_silences(source, ffmpeg, args.threshold, args.min_silence) except RuntimeError as error: print(f"Ошибка анализа: {error}", file=sys.stderr) return 2 boundaries = [0.0] end_boundary = total for start, end in silences: if start <= 0.05: boundaries[0] = max(boundaries[0], min(end, total)) elif end >= total - 0.05: end_boundary = min(end_boundary, max(0.0, start)) else: boundaries.append((start + end) / 2) boundaries.append(end_boundary) boundaries = sorted(set(round(value, 3) for value in boundaries)) segments: list[tuple[float, float]] = [] for index in range(len(boundaries) - 1): begin = boundaries[index] finish = boundaries[index + 1] if finish - begin >= args.min_segment: segments.append((begin, finish)) if not silences: print("Тишина не найдена. Проверьте порог --threshold.", file=sys.stderr) return 1 if not segments: print("После фильтрации не осталось фрагментов.", file=sys.stderr) return 1 out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) prefix = args.prefix or source.stem done = 0 for number, (begin, finish) in enumerate(segments, start=1): destination = out_dir / f"{prefix}-{number:03d}.{args.format}" if destination.exists() and not args.overwrite: print(f"Пропуск: {destination}") continue command = [ ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", str(source), "-ss", f"{begin:.3f}", "-t", f"{finish - begin:.3f}", "-map", "0:a", "-map_metadata", "0", ] command += codec_args(args.format) 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"Ошибка фрагмента {number}: {result.stderr.strip()}", file=sys.stderr) continue print(f"Готово: {destination.name} ({begin:.2f} - {finish:.2f})") done += 1 print(f"Итог: создано {done} из {len(segments)} фрагментов") return 0 if done else 2 if __name__ == "__main__": raise SystemExit(main())