Skip to content

Instantly share code, notes, and snippets.

@basperheim
Created May 12, 2026 17:47
Show Gist options
  • Select an option

  • Save basperheim/8f3722ee26d01bfc2d9f48a9ed3e6ac3 to your computer and use it in GitHub Desktop.

Select an option

Save basperheim/8f3722ee26d01bfc2d9f48a9ed3e6ac3 to your computer and use it in GitHub Desktop.
Shell helper for retagging M4B audiobooks with FFmpeg. Copies only audio streams, preserves chapters, writes clean title/album/artist/genre/date/comment metadata, and avoids common bin_data/text stream remux failures.
fix_m4b_tags() {
local input_file="$1"
local title="$2"
local album="$3"
local artist="${4:-}"
local genre="${5:-Audiobook}"
local date="${6:-}"
local comment="${7:-}"
if [[ -z "$input_file" || -z "$title" || -z "$album" ]]; then
echo "Usage:"
echo " fix_m4b_exif input.m4b \"Title\" \"Album\" [Artist] [Genre] [Year] [Comment]"
return 1
fi
if [[ ! -f "$input_file" ]]; then
echo "Error: file not found: $input_file"
return 1
fi
if ! command -v ffmpeg >/dev/null 2>&1; then
echo "Error: ffmpeg is not installed or not in PATH."
return 1
fi
local filename="${input_file##*/}"
local dir="${input_file%/*}"
if [[ "$dir" == "$input_file" ]]; then
dir="."
fi
local name="${filename%.*}"
local ext="${filename##*.}"
local output_file="${dir}/${name}-fixed-tags.${ext}"
local cmd=(
ffmpeg
-y
-i "$input_file"
# Copy only audio streams. Do not blindly use "-map 0",
# because some M4B files contain weird text/bin_data streams
# that the ipod/m4b muxer rejects.
-map 0:a
# Keep chapter metadata without copying the problematic stream directly.
-map_chapters 0
-c copy
-metadata "title=$title"
-metadata "album=$album"
-metadata "genre=$genre"
)
if [[ -n "$artist" ]]; then
cmd+=(-metadata "artist=$artist")
fi
if [[ -n "$date" ]]; then
cmd+=(-metadata "date=$date")
fi
if [[ -n "$comment" ]]; then
cmd+=(-metadata "comment=$comment")
fi
cmd+=("$output_file")
echo "Running FFmpeg command:"
printf ' %q' "${cmd[@]}"
echo
echo
"${cmd[@]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment