Created
March 31, 2019 23:28
-
-
Save reznor244/674a18ff652f73cb5d9ad7ca1a4f2a2e to your computer and use it in GitHub Desktop.
audio-extractor: Uses ffmpeg to extract the audio from a video file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
assert_is_numeric() | |
{ | |
re='^[0-9]+$' | |
if ! [[ $1 =~ $re ]] ; then | |
echo "Error: Value '$1' is not a number" >&2; exit 1 | |
fi | |
} | |
declare -a req=("ffmpeg" "ffprobe" "basename" "grep" "sed") | |
for cmd in "${req[@]}" | |
do | |
command -v $cmd >/dev/null 2>&1 || { echo "Required command not found: $cmd"; exit 1; } | |
done | |
start=0 | |
trim=0 | |
while getopts ":s:e:" opt; do | |
case $opt in | |
s) | |
start=$OPTARG | |
assert_is_numeric "$start" | |
;; | |
e) | |
trim=$OPTARG | |
assert_is_numeric "$trim" | |
;; | |
:) | |
echo "Option -$OPTARG requires an argument." >&2 | |
exit 1 | |
;; | |
esac | |
done | |
shift $(expr $OPTIND - 1 ) | |
#[ $1 ] || { echo "Usage: $0 file1 [file2]..."; } | |
for i in "$@" | |
do | |
[ -f "$i" ] || { echo "File $i not found!"; exit 1; } | |
done | |
echo "" | |
echo "Trimmed from start : ${start} seconds" | |
echo "Trimmed from end : ${trim} seconds" | |
echo "" | |
for file in "$@" | |
do | |
echo "=======================================================" | |
if [ -f "$file" ]; then | |
infile=$(basename "$file") | |
outfile="${infile%.*}.m4a" | |
echo -e "\nProcessing '$infile'\n" | |
if [ ! -f "$outfile" ]; then | |
duration=$(ffprobe -i "$infile" -show_entries format=duration -v quiet | grep "duration" | sed -e "s/duration=//" | sed "s/\..*$//") | |
tduration=$((duration-start-trim)) | |
echo "Initial Duration : $duration seconds" | |
echo "Target Duration : $tduration seconds" | |
# Extract audio from video. | |
ffmpeg -ss $start -t $tduration -i "$infile" -map 0:a -c copy "$outfile" -v quiet | |
echo -e "\nExtracted audio to '$outfile'" | |
else | |
echo "File '$outfile' already exists." | |
fi | |
else | |
echo "File '$file' not found." | |
fi | |
echo "" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment