Skip to content

Instantly share code, notes, and snippets.

@muness
Created August 15, 2020 15:33
Show Gist options
  • Save muness/41572533d01109b3e3abe4925a43c0d2 to your computer and use it in GitHub Desktop.
Save muness/41572533d01109b3e3abe4925a43c0d2 to your computer and use it in GitHub Desktop.
Splits OpenAudible decrypted mp3 files to a form suitable for Garmin watch audiobook playback
#!/bin/bash
# Based on: http://crunchbang.org/forums/viewtopic.php?id=38748#p414992
# m4bronto
# Metadata looks like this:
# Chapter #0:0: start 0.000000, end 1290.013333
# first _ _ start _ end
while [ $# -gt 0 ]; do
# extract mp3 metadata to tmp.txt
ffmpeg -i "$1" 2> tmp.txt
# extract author name
author=`cat tmp.txt | grep -w artist | head -n 1 | cut -d ' ' -f16-`
# extract book name
book=`cat tmp.txt | grep -w album | head -n 1 | cut -d ' ' -f17- | sed "s/\s*(Unabridged)//"`
# extract last chapter number
max_chapter=`cat tmp.txt | grep -w title | grep -w Chapter | tail -n 1 | cut -d ' ' -f20-`
# figure out the max number of digits in a chapter name (to be able to generate 0 padded file names and titles later)
max_chapter_digits_p1=`echo $max_chapter | wc -c`
max_chapter_digits=$(( $max_chapter_digits_p1 -1 ))
mkdir -p "$author"/"$book"
# extract the book cover to cover.png
rm -f cover.png
ffmpeg -i "$1" -an -vcodec copy cover.png 2>/dev/null
rm -f "$author/$book/cover.png"
cp cover.png "$author"/"$book"
# iterate over the chapters
while read -r first _ _ start _ end; do
if [[ $first = Chapter ]]; then
read # discard line with Metadata:
read _ _ chapter_w_prefix
chapter=`echo $chapter_w_prefix | sed "s/Chapter //"`
# pad the chapter number with 0s
printf -v padded_chapter "%0${max_chapter_digits}g" $chapter
rm -f in.mp3
# split the chapter out to its own in.mp3 file, set the title to e.g. Chapter 02/22 - Book Name
ffmpeg -vsync 2 \
-i "$1" \
-vn \
-codec copy \
-ss "${start%?}" -to "$end" \
-map_metadata 0 -id3v2_version 3 -write_id3v1 1 \
-metadata title="$chapter_w_prefix/$max_chapter - $book" \
-metadata track="$chapter/$max_chapter" \
-f mp3 in.mp3 </dev/null
rm -f "$author/$book/$padded_chapter.mp3"
# add the cover to the mp3, renaming it from in.mp3 to <chapter with 0 padding>.mp3, e.g. 02.mp3
ffmpeg -i in.mp3 -i cover.png -map 0:0 -map 1:0 -c copy -id3v2_version 3 \
-metadata:s:v title="Album cover" -metadata:s:v comment="Cover (front)" \
"$author/$book/$padded_chapter.mp3" </dev/null
# rm in.mp3
fi
done <tmp.txt
rm tmp.txt
rm cover.png
shift
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment