Skip to content

Instantly share code, notes, and snippets.

@Skinner927
Last active February 19, 2016 18:06
Show Gist options
  • Save Skinner927/4d40ecc756c5eed33e9e to your computer and use it in GitHub Desktop.
Save Skinner927/4d40ecc756c5eed33e9e to your computer and use it in GitHub Desktop.
Recursively split directory of mp3s by X minute chunks. Requires ffmpeg.
#!/bin/bash
min=10; #num minutes to split by
VERBOSE=false
QUIET=false
TEST=false
while getopts ':vqt:nh' opt; do
case $opt in
v) VERBOSE=true ;;
q) QUIET=true ;;
t) min=$OPTARG ;;
n) TEST=true ;;
h) echo "Split MP3 files"; echo "Options:";
echo "-v verbose"; echo "-q quiet"; echo "-n noop - test mode";
echo "-t specify a time in minutes to split by. Default is "$min;
exit 0;
;;
\?) echo "Unexpected option -$OPTARG" >&2; exit 1; ;;
:) echo "Option -$OPTARG requires an argument." >&2; exit 1; ;;
esac
done
# http://stackoverflow.com/questions/12199631/convert-seconds-to-hours-minutes-seconds-in-bash
convertsecs() {
((h=${1}/3600))
((m=(${1}%3600)/60))
((s=${1}%60))
printf "%02d:%02d:%02d\n" $h $m $s
}
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for file in $(find . -name '*.mp3' -type f -not -path '*/\.*'); do
#secLen=$(mdls "$file" | grep kMDItemDurationSeconds | awk '{print $3}')
secLen=$(ffmpeg -i "$file" -codec copy 2>&1 | grep Duration | awk '{split(gensub(/\,/,"","g",$2),a,":"); print (a[1]*60*60)+(a[2]*60)+(a[3])}')
splits=$(echo "($secLen/($min*60)) + 1" | bc )
if [ $splits -lt 3 ]; then
$QUIET || echo "Skipping small file: $file"
continue
fi
$QUIET || echo 'Splitting file: '$file' | sec: '$secLen' | split: '$splits
X=0; while( [ $X -lt $splits ] ); do
start=$(convertsecs $((min*60*X)))
output="$(echo $file"_pt"$(($X+1))".mp3")"
$QUIET || $VERBOSE && echo "Split "$X" start: "$start
$TEST || ffmpeg -v quiet -i "$file" -acodec copy -t 00:$min:00 -ss $start "$output"
X=$((X+1))
done;
#remove the orignal file
$TEST || rm "$file"
done;
IFS=$SAVEIFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment