dotfiles

personal dotfiles
git clone anongit@rnpnr.xyz:dotfiles.git
Log | Files | Refs | Feed | Submodules

extract-audio (1261B)


      1 #!/bin/sh
      2 
      3 # extract audio from video files
      4 # useful for passive immersion
      5 
      6 usage() {
      7 	echo "usage: $0 [-n] [-d outdir] [-l lang] file ..."
      8 	exit 1
      9 }
     10 
     11 while getopts "d:l:n" arg; do
     12 	case "${arg}" in
     13 	d) outdir="${OPTARG}" ;;
     14 	l) lang="${OPTARG}" ;;
     15 	n) COUNT=0 ;;
     16 	*) usage ;;
     17 	esac
     18 done
     19 
     20 shift $((OPTIND - 1))
     21 
     22 [ $# -gt 0 ] || usage
     23 
     24 out="${outdir:-.}"
     25 lang=${lang:-jpn}
     26 
     27 [ -d "$out" ] || mkdir -p "$out"
     28 
     29 IFS=
     30 for f in $*; do
     31 	# construct track title and new filename
     32 	t=$(echo $f | cut -d . -f 1 | \
     33 	    sed -e 's:\[.*\]::g; s:(.*)::g' \
     34 	        -e 's:^ *::; s: *$::' \
     35 	        -e 's:^_*::; s:_*$::')
     36 	newf=$out/$t.opus
     37 
     38 	if [ $COUNT ]; then
     39 		COUNT=$((COUNT + 1))
     40 		newf=$(printf "%s/%02d %s.opus" $out $COUNT $t)
     41 	fi
     42 
     43 	# find a stream index for desired audio track
     44 	idx=$(ffprobe -of compact=nk=1:s=. -v error \
     45 	      -show_entries stream=index,codec_type:stream_tags=language \
     46 	      $f | \
     47 	      awk -F . '/audio.'$lang'/ { print $2; exit }')
     48 
     49 	# if no audio tracks have specified lang fall back to a:0
     50 	idx=${idx:-a:0}
     51 
     52 	case $f in
     53 	*.mkv|*.mp4)
     54 		ffmpeg -loglevel error -stats \
     55 		       -i $f -map 0:$idx \
     56 		       -map_metadata -1 \
     57 		       -c libopus -mapping_family 255 \
     58 		       -metadata title=$t \
     59 		       $newf
     60 		;;
     61 	*) ;;
     62 	esac
     63 done