Date created: Friday, April 28, 2017 10:01:28 AM. Last modified: Sunday, January 27, 2019 11:45:48 AM

Split MP3 by Seconds

A simple script to load timings (in seconds) from a text file and split a long MP3 into multiple smaller MP3 files:

#!/bin/bash

set -eu

ts_get_sec()
{
  read -r h m s <<< $(echo $1 | tr ':' ' ' )
  echo $(((60*60*$((10#$h)))+(60*$((10#$m)))+$((10#$s))))
}

while IFS='' read -r line || [[ -n "$line" ]]; do
    NAME=$(echo "$line" | awk  'BEGIN {FS="\t"}; {print $1};')
    START=$(echo "$line" | awk  'BEGIN {FS="\t"}; {print $2};')
    END=$(echo "$line" | awk  'BEGIN {FS="\t"}; {print $3};')
    START=$(ts_get_sec $START)
    END=$(ts_get_sec $END)
    DIFF=$((END-START))
    LENGTH="00:$((DIFF/60)):$((DIFF%60))"
    avconv -i "$1" -acodec copy -ss $START -t $LENGTH -y "$NAME.mp3"
done < timings.txt
# Tab seperated file:
# filename-TAB-start-TAB-end
$ cat timings.txt

1. Track 1	00:00:00	00:04:43
2. Track 2	00:04:43	00:08:45
3. Track 3	00:08:45	00:13:01

Previous page: Rsync with Notification
Next page: Stuck In Time