#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --out <файл> [--copy] [--force] <файл1> <файл2> ..." } out="" copy=0 force=0 inputs=() while [[ $# -gt 0 ]]; do case "$1" in --out) out="${2:-}"; shift 2 ;; --copy) copy=1; shift ;; --force) force=1; shift ;; -h|--help) usage; exit 0 ;; --) shift; inputs+=("$@"); break ;; *) if [[ -f "$1" ]]; then inputs+=("$1") shift else echo "Неизвестный аргумент или файл: $1" >&2 usage >&2 exit 2 fi ;; esac done if [[ -z "$out" ]]; then usage >&2 exit 2 fi if [[ "${#inputs[@]}" -lt 2 ]]; then echo "Нужно минимум два входных файла." >&2 exit 2 fi if ! command -v ffmpeg >/dev/null 2>&1; then echo "ffmpeg не найден. Установите FFmpeg." >&2 exit 1 fi if [[ -e "$out" && "$force" -eq 0 ]]; then echo "Файл уже существует: $out. Добавьте --force для перезаписи." >&2 exit 1 fi outdir="$(dirname "$out")" mkdir -p "$outdir" out="$(cd "$outdir" && pwd)/$(basename "$out")" tmpdir="$(mktemp -d)" trap 'rm -rf "$tmpdir"' EXIT list="$tmpdir/files.txt" : > "$list" absolute_inputs=() for file in "${inputs[@]}"; do if [[ ! -f "$file" ]]; then echo "Файл не найден: $file" >&2 exit 2 fi if [[ "$file" == *"'"* ]]; then echo "Имя с одинарной кавычкой не поддержано: $file" >&2 exit 2 fi absolute="$(cd "$(dirname "$file")" && pwd)/$(basename "$file")" absolute_inputs+=("$absolute") printf "file '%s'\n" "$absolute" >> "$list" done if [[ "$copy" -eq 1 ]]; then ffmpeg -hide_banner -loglevel error -nostdin -f concat -safe 0 -i "$list" \ -c copy -map_metadata 0 -y "$out" else case "${out,,}" in *.mp3) codec=(-c:a libmp3lame -b:a 192k) ;; *.m4a) codec=(-c:a aac -b:a 192k) ;; *.wav) codec=(-c:a pcm_s16le) ;; *.flac) codec=(-c:a flac) ;; *) codec=(-c:a libmp3lame -b:a 192k) ;; esac input_args=() filter="" concat_inputs="" index=0 for file in "${absolute_inputs[@]}"; do input_args+=(-i "$file") filter+="[${index}:a]aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo[a${index}];" concat_inputs+="[a${index}]" index=$((index + 1)) done filter+="${concat_inputs}concat=n=${#absolute_inputs[@]}:v=0:a=1[out]" ffmpeg -hide_banner -loglevel error -nostdin "${input_args[@]}" \ -filter_complex "$filter" -map "[out]" "${codec[@]}" \ -ar 44100 -ac 2 -map_metadata 0 -y "$out" fi echo "Готово: $out" echo "Склеено файлов: ${#inputs[@]}"