#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 <видео|папка> [выходная папка] [m4a|mp3|wav] [--format m4a|mp3|wav] [--copy]" } src="" out="" format="m4a" format_flag=0 copy=0 positional=() while [[ $# -gt 0 ]]; do case "$1" in --copy) copy=1; shift ;; --format) format="${2:-}"; format_flag=1; shift 2 ;; -h|--help) usage; exit 0 ;; -*) echo "Неизвестный аргумент: $1" >&2 usage >&2 exit 2 ;; *) positional+=("$1") shift ;; esac done src="${positional[0]:-}" out="${positional[1]:-}" if [[ "${#positional[@]}" -ge 3 && "$format_flag" -eq 0 ]]; then format="${positional[2]}" fi if [[ -z "$src" ]]; then usage >&2 exit 2 fi if [[ ! -e "$src" ]]; then echo "Источник не найден: $src" >&2 exit 2 fi case "$format" in m4a|mp3|wav) ;; *) echo "Формат должен быть m4a, mp3 или wav." >&2; exit 2 ;; esac if ! command -v ffmpeg >/dev/null 2>&1; then echo "ffmpeg не найден. Установите FFmpeg." >&2 exit 1 fi if [[ "$copy" -eq 1 && "$format" != "m4a" ]]; then echo "Режим --copy поддержан только для m4a." >&2 exit 2 fi if [[ -d "$src" ]]; then root="$src" if [[ -z "$out" ]]; then out="$root/extracted" fi mapfile -d '' files < <( find "$root" -maxdepth 1 -type f \ \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.mov' \ -o -iname '*.webm' -o -iname '*.avi' -o -iname '*.m4v' \) \ -print0 ) else files=("$src") if [[ -z "$out" ]]; then out="$(dirname "$src")/extracted" fi fi mkdir -p "$out" if [[ "${#files[@]}" -eq 0 ]]; then echo "Видеофайлы не найдены." >&2 exit 1 fi count=0 failed=0 for file in "${files[@]}"; do name="$(basename "$file")" name="${name%.*}" dest="$out/$name.$format" if [[ -e "$dest" ]]; then echo "Пропуск: $dest уже существует" continue fi if [[ "$copy" -eq 1 ]]; then if ffmpeg -hide_banner -loglevel error -nostdin -n -i "$file" \ -vn -map 0:a:0 -c:a copy -map_metadata 0 "$dest"; then echo "Готово: $(basename "$file") -> $(basename "$dest")" count=$((count + 1)) else echo "Ошибка копирования: $file" >&2 failed=$((failed + 1)) fi continue fi case "$format" in m4a) codec=(-c:a aac -b:a 192k -movflags +faststart) ;; mp3) codec=(-c:a libmp3lame -b:a 192k) ;; wav) codec=(-c:a pcm_s16le) ;; esac if ffmpeg -hide_banner -loglevel error -nostdin -n -i "$file" \ -vn -map 0:a:0 -map_metadata 0 "${codec[@]}" "$dest"; then echo "Готово: $(basename "$file") -> $(basename "$dest")" count=$((count + 1)) else echo "Ошибка: $file" >&2 failed=$((failed + 1)) fi done echo "Итог: готово $count, ошибок $failed" [[ "$failed" -eq 0 ]]