📜 ⬆️ ⬇️

Download Youtube playlist in mp3 format with one bash-script

It so happened that at the moment my working laptop is equipped with only 2GB of RAM. In this regard, it became necessary to optimize the browser, because with a large number of open tabs, memory becomes insufficient and a swap-section is used, which leads to brakes.

Music helps me in my work, usually it is an open tab with a Youtube playlist. So this tab in the workflow eats up to 500MB (!) And even more (Google Chrome).

This state of affairs forced us to write a bash script that receives a playlist ID at the entrance, and mp3 files at the output that you can listen to in your favorite player, for example, in the MOC:
MOC

')
You cannot download mp3 from Youtube, so we divide the process into 3 steps:
  1. download flv
  2. extract the audio track
  3. delete temporary flv


Just in case, I remind you that the playlist ID is a get-parameter "list".

Dependencies:
sudo apt-get install youtube-dl ffmpeg libavcodec-extra-53 



Actually the script itself, commented in detail ( download ):
 #!/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 "instrumental hip-hop beats" 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 #  Youtube API     # 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 # c ID     songs 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 #       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.  flv 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 # 3.  flv rm "$flv_path" fi done 


I hope this script is not only useful to me and will save a lot of gigabytes of RAM from the masters.

Source: https://habr.com/ru/post/183172/


All Articles