Re-order id3 track numbers of multi-disc audiobook

Alec Jacobson

September 03, 2015

weblog/

Yesterday I was floundering trying to get iTunes and the iPhone iBook app to iFunctionCorrectly. I have an audiobook composed of multiple mp3s ripped from multiple cds. The track names look like:

1-01-madame-bovary-1a.mp3
1-02-madame-bovary-1b.mp3
1-03-madame-bovary-1c.mp3
...
2-01-madame-bovary-2a.mp3
2-02-madame-bovary-2b.mp3
2-03-madame-bovary-2c.mp3
...
11-01-madame-bovary-11a.mp3
11-02-madame-bovary-11b.mp3
11-03-madame-bovary-11c.mp3
...

This is already unfortunate because lexicographically they sort to:

1-01-madame-bovary-1a.mp3
1-02-madame-bovary-1b.mp3
1-03-madame-bovary-1c.mp3
...
11-01-madame-bovary-11a.mp3
11-02-madame-bovary-11b.mp3
11-03-madame-bovary-11c.mp3
...
2-01-madame-bovary-2a.mp3
2-02-madame-bovary-2b.mp3
2-03-madame-bovary-2c.mp3
...

iTunes deals with this reasonably well. The bigger problem was the id3 tags of these files. All files had the same artist and album.

1-01-madame-bovary-1a.mp3
1-02-madame-bovary-1b.mp3
1-03-madame-bovary-1c.mp3
...

had track numbers 1/30, 2/30, 3/30 etc. and all had part number 1/11 (part 1 of an 11 part set). However, iBook refused to sort these by part number then track number. Instead, only sorting by track number, getting this:

1-01-madame-bovary-1a.mp3
2-01-madame-bovary-2a.mp3
...
11-01-madame-bovary-11a.mp3
1-02-madame-bovary-1b.mp3
2-02-madame-bovary-2b.mp3
11-02-madame-bovary-11b.mp3
...
1-03-madame-bovary-1c.mp3
2-03-madame-bovary-2c.mp3
11-03-madame-bovary-11c.mp3
...

I tried converting everything into a single giant mp3 file using ffmpeg:

ls *.mp3 | sort -n | sed -e "s/^\(.*\)$/file '\1'/" > concat.txt
ffmpeg -f concat -i concat.txt -y -vn -acodec copy -threads 3 madame-bovary.mp3

or a single m4b file:

ffmpeg -f concat -i concat.txt -y -vn -acodec libfaac -ab 64k -ar 44100 -threads 3 -f mp4 madame-bovary.m4b

but these files were 900MB and 350MB and iBooks seems to choke on that size.

Finally, my solution is to re-order all of the track numbers to increment across parts. I achieved this with a little bash script, I saved in track_number_explode.sh

#!/bin/bash
USAGE="track_number_explode [path to directory of mp3s]"
if [ -z "$1" ]; then
    echo "Usage: $USAGE"
    exit 1
fi
OLD_DIR=$(pwd)
cd "$1"
MP3S=$(ls *.mp3 | sort -n)
N=$(echo -e "$MP3S" | wc -l)
# cheap way to clear leading spaces
N=$((N+0))
T="1"
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for mp3 in $MP3S; do
  id3v2 --id3v2-only -T "$T/$N" "$mp3"
  # strip id3.1 as it can handle large track numbers
  id3v2 -s "$mp3" &>/dev/null
  T=$((T+1))
done
IFS=$SAVEIFS
cd "$OLD_DIR"

Then I run this on the directory containing my mp3s

track_number_explode.sh madame-bovary/

Finally I load these onto the iPhone, select all of them, right-click and choose Get Info > Options and set media kind to Audiobook.