Skip to content

Instantly share code, notes, and snippets.

@matheusfaustino
Created January 27, 2020 02:49
Show Gist options
  • Save matheusfaustino/bf4a350e78535609569f79be16502d65 to your computer and use it in GitHub Desktop.
Save matheusfaustino/bf4a350e78535609569f79be16502d65 to your computer and use it in GitHub Desktop.
Download youtube video setting a period of time and extract audio from it
#!/bin/bash
function title(){
echo "##########################"
echo "## $1 ##"
echo "##########################"
}
# first param is the CSV file
FILE_CSV=$1
# folders output
FOLDER_VIDEO="$PWD/video"
FOLDER_AUDIO="$PWD/audio"
# config to read CSV file by comma SHELL
OLDIFS=$IFS
IFS=','
[ ! -f $FILE_CSV ] && { echo "$FILE_CSV file not found"; exit 99; }
[ ! -d $FOLDER_VIDEO ] && { echo "$FOLDER_VIDEO folder not created"; exit 98; }
[ ! -d $FOLDER_AUDIO ] && { echo "$FOLDER_AUDIO folder not created"; exit 97; }
echo "Reading: $FILE_CSV ..."
while read data youtube_link title cap_ver inicio fim
do
if [ -z "$youtube_link" ]
then
continue;
fi
# remove accentuation
title=`echo $title | sed -e 'y/āáǎàçēéěèīíǐìōóǒòūúǔùǖǘǚǜüĀÁǍÀĒÉĚÈĪÍǏÌŌÓǑÒŪÚǓÙǕǗǙǛÜ/aaaaceeeeiiiioooouuuuuuuuuAAAAEEEEIIIIOOOOUUUUUUUUU/'`
title "Downloading and convert $title to audio"
echo "Downloading video $youtube_link ..."
youtube-dl --postprocessor-args "-ss $inicio -to $fim" $youtube_link -o "$FOLDER_VIDEO/$title.%(ext)s"
echo "Copying file to audio folder to extract audio..."
folderVideoFile=`echo $(ls $FOLDER_VIDEO/$title* | head -n1)` # extract file name from wildcard
cp $folderVideoFile "$FOLDER_AUDIO/"
folderAudioFile=`echo $(ls $FOLDER_AUDIO/$title* | head -n1)` # extract file name from wildcard
audioLength=${#folderAudioFile}
audioFinalFile="${folderAudioFile:0:audioLength - 4}.mp3"
if [ ! -f $audioFinalFile ]
then
echo "Extracting audio from video..."
# @see https://www.igorkromin.net/index.php/2016/12/23/prevent-errors-during-ffmpeg-execution-in-a-loop/
ffmpeg -i $folderAudioFile -f mp3 -ab 320000 -vn $audioFinalFile < /dev/null;
fi
echo "Cleaning temp files"
rm $folderAudioFile;
# exit 1;
done < $FILE_CSV
IFS=$OLDIFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment