Files
m4b_mp3/m4b_mp3.sh
2025-07-09 18:12:26 +02:00

77 lines
2.7 KiB
Bash
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# Locale für Dezimalzahlen auf C setzen, damit Punkt als Dezimaltrennzeichen genutzt wird
export LC_NUMERIC=C
# Prüfen, ob alle Tools vorhanden sind
for cmd in ffmpeg ffprobe jq gum id3v2; do
command -v "$cmd" >/dev/null 2>&1 || {
echo "Fehler: '$cmd' ist nicht installiert. Bitte installieren." >&2
exit 1
}
done
# Ungültige Zeichen in Dateinamen ersetzen (z.B. ":" durch "-")
for f in *.m4b; do
safe_name=$(echo "$f" | sed 's/[:\/\\<>*?"|]/-/g')
if [[ "$f" != "$safe_name" ]]; then
mv -- "$f" "$safe_name"
echo "📁 Umbennen: '$f' → '$safe_name'"
fi
done
track=1
for i in *.m4b; do
title=$(basename "$PWD" | cut -d ',' -f 1)
full_file_path="$i"
echo "🎧 Bearbeite Datei: $full_file_path"
# Kapitel als JSON auslesen
chapters_json=$(ffprobe -loglevel error -print_format json -show_chapters "$full_file_path")
total_chapters=$(jq '.chapters | length' <<< "$chapters_json")
echo "📚 Enthaltene Kapitel: $total_chapters"
for (( idx=0; idx<total_chapters; idx++ )); do
start=$(jq -r ".chapters[$idx].start_time" <<< "$chapters_json")
end=$(jq -r ".chapters[$idx].end_time" <<< "$chapters_json")
chapter=$(jq -r ".chapters[$idx].tags.title // \"Kapitel $((idx+1))\"" <<< "$chapters_json")
duration=$(printf "%.3f" "$(echo "$end - $start" | bc -l)")
# Kapitelname optional formatieren (z.B. Nummern nullpadden)
chapter=$(sed -re ":r;s/\b[0-9]{1,$((1))}\b/0&/g;tr" <<< "$chapter")
# base_name="${title} - ${chapter}"
# zweistellige Tracknummer erzeugen
track_padded=$(printf "%02d" "$track")
safe_chapter=$(echo "$chapter" | sed 's/[:\/\\<>*?"|]/-/g')
base_name="${track_padded} - ${safe_chapter}"
# base_name="${track_padded} - ${chapter}"
chapter_file="${base_name}.mp3"
# Suffix anhängen bei Dopplungen
suffix=1
while [[ -e "$chapter_file" ]]; do
chapter_file="${base_name}_(${suffix}).mp3"
suffix=$((suffix + 1))
done
gum spin --title "Extrahiere Kapitel $((idx+1))/$total_chapters: $chapter" -- \
ffmpeg -loglevel error -stats -ss "$start" -i "$full_file_path" -t "$duration" \
-avoid_negative_ts make_zero -map 0:a:0 -codec:a libmp3lame -ar 44100 -b:a 192k \
-metadata track="$track" "$chapter_file"
id3v2 --song "$chapter" "$chapter_file"
id3v2 --album "$title" "$chapter_file"
id3v2 --track "$track" "$chapter_file"
id3v2 --genre "Audiobooks" "$chapter_file"
track=$((track + 1))
done
done
gum style --foreground 10 --bold "✅ Alle Kapitel erfolgreich extrahiert und getaggt."