dotfiles

My personal dotfiles 💠️

mp3-dl (1286B)

      1 #!/bin/sh
      2 # Downloads MP3 files from YouTube with youtube-dl
      3 # 
      4 # Copyright (C) 2020 Pablo Emilio Escobar Gaviria.
      5 # Free use of this software is granted under the terms of the GPL-3.0 License.
      6 
      7 getFormat() {
      8   youtube-dl --default-search 'ytsearch' -F "$1" \
      9     | sed '/audio only/!d' \
     10     | fzf --prompt='Which format do you prefer? ' \
     11     | cut -d ' ' -f1
     12 }
     13 
     14 case "$1" in
     15   -h|--help)
     16     echo 'Usage: mp3-dl (URL|NAMEOFVIDEO) [MP3FILE]'
     17     ;;
     18   *)
     19     url="$1"
     20 
     21     case "$2" in
     22       '')
     23         output="$(youtube-dl --default-search 'ytsearch' --get-title "$url").mp3"
     24         ;;
     25       *.mp3)
     26         output="$2"
     27         ;;
     28       *)
     29         output="$2.mp3"
     30         ;;
     31     esac
     32 
     33     # Prompts the user to ask for the appropriate format to download
     34     format="$(getFormat "$url")"
     35     if [ -z "$format" ] 
     36     then
     37       echo "Operation cancelled" 
     38       exit
     39     fi
     40 
     41     # Download the source from YouTube
     42     source_file="$(mktemp tmp.XXXXXXXXXX."$format")"
     43     youtube-dl --default-search 'ytsearch' "$url" -o "$source_file"
     44 
     45     # Convert the source to MP3 and clean-up the mess
     46     if [ "$format" = 'mp3' ]
     47     then
     48       mv "$source_file" "$output"
     49     else
     50       ffmpeg -i "$source_file" -c:a libmp3lame -ac 2 -q:a 2 "$output"
     51       rm "$source_file"
     52     fi
     53     ;;
     54 esac