#!/bin/bash
# Desc: Split an audio file by chapter
# Depends: ffmpeg, jq
# Version: 0.0.1
# Ref/Attrib: [1] Hasan Arous. MIT license. https://unix.stackexchange.com/a/612124
#             [2] John Smith. https://unix.stackexchange.com/a/712600

in="$1";
out="$2";
splits="";
n=0;
while read start end title; do
    newTitle="$(echo "$title" | sed "s/ /_/g")";
    newTitle="$(printf "%02d..%s" "$n" "$newTitle")";
    splits="$splits -c copy -ss $start -to $end $out/$newTitle.m4b";
    ((n++));
done <<< $(ffprobe -i "$in" -print_format json -show_chapters \
  | jq -r '.chapters[] | .start_time + " " + .end_time + " " + (.tags.title | sub(" "; "_"))');
ffmpeg -i "$in" $splits;

# Author: Steven Baltakatei Sandoval
# License: GPLv3+
