Skip to content

Instantly share code, notes, and snippets.

@uugan
Last active January 27, 2016 19:48
Show Gist options
  • Save uugan/5779408 to your computer and use it in GitHub Desktop.
Save uugan/5779408 to your computer and use it in GitHub Desktop.
Youtube playlist video to mp3 downloader bash script sudo apt-get install youtube-dl ffmpeg or libavcodec-extra-53
#!/bin/bash
usage='usage:
./get_youtube_playlist <playlist_id> <target_folder> <num_songs>
target_folder: (default: songs will be downloaded in current folder)
num_songs: number of songs to get (default: 50)
examples:
./get_youtube_playlist RD02HIkZaLeuF9k
./get_youtube_playlist RD02HIkZaLeuF9k "my jazz" 10
'
playlist_id=$1
target_folder=$2
num_songs=$3
if [ -z "$playlist_id" ]; then
echo "$usage"
exit 1
fi
if ! [[ "$num_songs" =~ ^[0-9]+$ ]] ; then
num_songs=50
fi
if [ -z "$target_folder" ]; then
target_folder='./'
elif [ ! -d "$target_folder" ]; then
echo "Parameter target_folder is incorrect, $usage"
exit 1
fi
# use youtube API for getting music list of playlist
# https://developers.google.com/youtube/2.0/developers_guide_protocol_playlist_search
youtube_api="`wget -qO- https://gdata.youtube.com/feeds/api/playlists/$playlist_id\?max-results\=$num_songs`"
if [ -z "$youtube_api" ]; then
echo "Playlist ID is incorrect, $usage"
exit 1
fi
# list of IDs into songs array
songs=(
$(echo $youtube_api | \
grep -P -o "<media:player url='.*?&" | \
grep -P -o "(\w|-){11}")
)
if [ -z "$songs" ]; then
echo "Nothing to do, $usage"
exit 1
fi
# work with each music video
for (( i = 1 ; i <= ${#songs[@]} ; i++ ))
do
youtube_id=${songs[$i-1]}
track_number=`printf "%0*d" 2 $i`
flv_path="$target_folder/$youtube_id.flv"
mp3_path="$target_folder/$track_number. $youtube_id.mp3"
# 1. download flv by youtube-dl
youtube-dl --audio-format=mp3 -o "$flv_path" "http://youtu.be/$youtube_id"
if [ -f "$flv_path" ]
then
# 2. flv -> mp3
#avconv -i "$flv_path" -y "$mp3_path" -acodec libmp3lame -ac 2 -ab 128k -vn
ffmpeg -i "$flv_path" -acodec libmp3lame -ac 2 -ab 128k -vn -y "$mp3_path"
# 3. delete flv
rm "$flv_path"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment