#!/bin/sh
# $Id: audio-extract,v 1.2 2017/09/05 02:03:19 friedman Exp $

# Use "-map 0:n -f fmt" to extract other elements.
# For example "-map 0:4 -f ass" to extract a subtitle stream.

extract()
{
    infile=$1; shift

    ext=`ffprobe -hide_banner "$infile" 2>&1 \
           | sed -ne '/.*Audio: \([^ ,]*\).*/!d' -e 's//\1/p' -e q`
    case $ext in
        aac ) ext=m4a ;;
    esac

    outfile=${infile##*/} outfile=${outfile%.*}.$ext
    ffmpeg -hide_banner \
           -copy_unknown \
           -v error \
           -i "$infile" \
           -acodec copy \
           "$@" \
           "$outfile" \
        && touch -r "$infile" "$outfile"
}

main()
{
    case $2 in
        -* ) extract "$@" ;;
        *  ) for f in "$@"; do
                 echo "$f"
                 extract "$f"
             done ;;
    esac
}

main "$@"

# eof
