#!/usr/bin/env sh
# Help menu
usage() {
printf "Usage: $0 [-f <format>] [-d <directory>] [link]" 1>&2
printf "
It downloads on a directory the audio from the provided link.
If no link is provided, clipboard content is used.
-f <format> Sets the format the audio will be downloaded on.
Default: ogg opus when possible, otherwise vorbis ogg.
-d <directory> Sets the directory where downloaded audio will be stored.
Default: \$HOME/Downloads/yt-dlp/
" >&2
exit 1
}
origin="$(pwd)"
dir="$HOME/Downloads/yt-dlp"
[ ! -d "$dir" ] && mkdir -p "$dir"
# To get options provided to the command
while getopts ":f:d:" option; do
case "${option}" in
f)
format="${OPTARG}"
;;
d)
dir="${OPTARG}"
;;
* | h)
usage
;;
esac
done
shift $((OPTIND-1))
cd "$dir"
if [ -z "$1" ]; then
link="$(xclip -o -selection clipboard)"
else
link="$1"
fi
[ -z "$format" ] && format="opus"
if [ "$format" = "opus" ]; then
filename="$(yt-dlp -x --audio-quality 0 --audio-format opus --get-filename "$link")"
filename="$(printf "$filename" | sed -r "s|\..*$||").opus"
yt-dlp -x --audio-quality 0 --audio-format opus "$link"
size="$(stat --printf="%s" "$filename")"
# Little hack to check if opus file is ok
if [ "$size" -lt 500000 ]; then
yt-dlp -x --audio-quality 0 --audio-format vorbis "$link"
rm "$filename"
fi
else
yt-dlp -x --audio-quality 0 --audio-format "$format" "$link"
fi
cd "$origin"