Почистить голосовую запись
Убирает низкий гул и шум, выравнивает громкость речи и сохраняет копию.
Что делает скрипт
Скрипт применяет фильтры highpass, lowpass, afftdn и dynaudnorm. Режим light подходит для диктофона, strong сильнее подавляет фон, но может задеть тихие согласные. Исходная запись не изменяется, результат сохраняется отдельным файлом.
- Режим strong может сделать тихую речь неестественной. Слушайте результат.
Быстрый старт
python clean_voice.py interview.wav --preset light
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python clean_voice.py voice.m4a --preset strong --out voice_clean.m4apython clean_voice.py ./recordings --recursive --out ./clean
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
winget install Gyan.FFmpeg
brew install ffmpeg
sudo apt install ffmpeg
clean_voice.py
#!/usr/bin/env python3
"""Базовая очистка голосовой записи через ffmpeg."""
from __future__ import annotations
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
AUDIO_EXTENSIONS = {'.wav', '.mp3', '.m4a', '.flac', '.ogg', '.aac', '.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 AUDIO_EXTENSIONS
)
elif path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
files.append(path)
else:
print(f'Пропуск: {path}', file=sys.stderr)
return sorted(set(files), key=lambda item: str(item).lower())
def codec_args(suffix: str) -> list[str]:
suffix = suffix.lower()
if suffix == '.mp3':
return ['-c:a', 'libmp3lame', '-b:a', '192k']
if suffix in {'.m4a', '.aac'}:
return ['-c:a', 'aac', '-b:a', '192k']
if suffix == '.flac':
return ['-c:a', 'flac']
if suffix == '.ogg':
return ['-c:a', 'libvorbis', '-q:a', '5']
if suffix == '.opus':
return ['-c:a', 'libopus', '-b:a', '96k']
return ['-c:a', 'pcm_s16le']
def main() -> int:
parser = argparse.ArgumentParser(description='Очистить голосовую запись')
parser.add_argument('inputs', nargs='+', type=Path, help='Файлы или папки')
parser.add_argument('-o', '--out', type=Path, default=Path('clean_voice'), help='Папка для результата')
parser.add_argument('--preset', choices=['light', 'strong'], default='light', help='Сила обработки')
parser.add_argument('--recursive', action='store_true', help='Обходить вложенные папки')
parser.add_argument('--overwrite', action='store_true', help='Перезаписать существующие файлы')
args = parser.parse_args()
if args.preset == 'strong':
filters = 'highpass=f=90,lowpass=f=11000,afftdn=nr=20:nf=-30,dynaudnorm=f=200:g=15:p=0.95'
else:
filters = 'highpass=f=80,lowpass=f=12000,afftdn=nr=10:nf=-25,dynaudnorm=f=150:g=12:p=0.9'
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}_clean{source.suffix}'
if destination.exists() and not args.overwrite:
print(f'Пропуск: {destination}')
skipped += 1
continue
command = [
ffmpeg, '-hide_banner', '-loglevel', 'error', '-nostdin',
'-i', str(source), '-af', filters, '-map', '0:a', '-map_metadata', '0',
]
command += codec_args(source.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'Готово: {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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.