Skip to content

Instantly share code, notes, and snippets.

@chriskempson
Last active May 24, 2020 08:54
Show Gist options
  • Save chriskempson/29e6e9ea2ca97f5a2a63befafc84d1ab to your computer and use it in GitHub Desktop.
Save chriskempson/29e6e9ea2ca97f5a2a63befafc84d1ab to your computer and use it in GitHub Desktop.
Converts a directory of video files to audio files with ffmpeg
#!/bin/bash
# Convert a directory of videos to audio files
#
# ## Requirements
# bc, ffmpeg
#
# ## Usage
# Call from a directory containing videos:
#
# video2audio 10 20 1 mp3
#
# Or, to accept all default values:
#
# video2audio
#
# The first argument is the amount of time (in seconds) to trim from the
# beginning of the audio file (default 0 seconds).
#
# The second argument is the amount of time (in seconds) to trim from the
# end of the audio file (default 0 seconds).
#
# The third argument is the audio track you would like to convert. By
# default the first track (0) will be used.
#
# The fourth argument is the format you would like the audio file to use
# (default mp3). See ffmpeg docs for a list of supported audio formats.
# The fourth argument is the name you would like to set for the artist and
# album title. If this is not set the name of the current directory will be
# used.
TRIM_START=${1:-0}
TRIM_END=${2:-0}
AUDIO_TRACK=${3:-0}
FORMAT=${4:-mp3}
OUTPUT_PATH="audio/"
ALBUM=${PWD##*/}
ARTIST=$ALBUM
mkdir -p "$OUTPUT_PATH"
declare -a TYPES=(
"mkv" "mp4" "avi" "wmv"
)
for TYPE in ${TYPES[@]}; do
for FILE in *.$TYPE; do
if [ -e "$FILE" ]; then
LENGTH=$(ffprobe -v 0 -show_entries FORMAT=duration -of compact=p=0:nk=1 "$FILE")
TRIM_END="$LENGTH - $TRIM_END" | bc
ffmpeg -y -ss $TRIM_START -t $TRIM_END -i "$FILE" -c:a $FORMAT -map 0:a:$AUDIO_TRACK -metadata title="${FILE%.*}" -metadata artist="$ARTIST" -metadata album="$ALBUM" "$OUTPUT_PATH${FILE%.*}.$FORMAT"
fi
done
done
@chriskempson
Copy link
Author

Updated to fix "Invalid stream specifier: audio." issue. "-c:audio" is no longer valid in ffmpeg.

@chriskempson
Copy link
Author

  • Added argument for selecting which audio track to extract
  • Audio is now output to an "audio" directory rather than dumped into the same folder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment