Last active
May 17, 2022 14:19
-
-
Save brkydnc/4f4b3c232fb0c3e7dff7d861c2bf7c1d to your computer and use it in GitHub Desktop.
Extract audios of the videos in a given playlist using yt-dlp and GNU parallel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function print_help_message() { | |
echo "Extracts audios from the videos in a given playlist using yt-dlp and GNU parallel" | |
echo | |
echo "USAGE: ${0} [options] <playlist_id>" | |
echo | |
echo "OPTIONS:" | |
echo "-h, --help Print this message." | |
echo "-o, --output DIR Download videos to DIR" | |
echo "-i, --ignore FILE Ignore the IDs in FILE" | |
echo "-s, --save FILE Save the IDs of the downloaded videos into FILE" | |
} | |
# Extracts the audio of a given video (id) as an mp3 file. | |
function extract_audio() { | |
yt-dlp \ | |
-q \ | |
--concurrent-fragments 4 \ | |
-x \ | |
--audio-quality 0 \ | |
--audio-format mp3 \ | |
-o "%(title)s.%(ext)s" \ | |
-P ${1} \ | |
${2} | |
} | |
# Export the function so that it can be passed to `parallel`. | |
export -f extract_audio | |
OUTPUT=$(pwd) | |
POSITIONAL_ARGS=() | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
-h|--help) | |
print_help_message | |
shift | |
exit 0 | |
;; | |
-o|--output) | |
OUTPUT="$2" | |
shift | |
shift | |
;; | |
-i|--ignore) | |
IGNORE="$2" | |
shift | |
shift | |
;; | |
-s|--save) | |
SAVE="$2" | |
shift | |
shift | |
;; | |
-*|--*) | |
echo "Unknown option: $1" | |
exit 1 | |
;; | |
*) | |
POSITIONAL_ARGS+=("$1") | |
shift | |
;; | |
esac | |
done | |
set -- "${POSITIONAL_ARGS[@]}" | |
if [ -z "$1" ] | |
then | |
echo "No playlist id specified" | |
exit 1 | |
fi | |
# Extract the ids of all the videos in the playlist | |
ID_LIST=$(yt-dlp --flat-playlist --get-id ${1} | sort) | |
if [ -n "$IGNORE" ] | |
then | |
if [ -e "$IGNORE" ] | |
then | |
# Filter ids that appear in the ignore file | |
ID_LIST=$(echo "$ID_LIST" | comm -23 - <(sort $IGNORE)) | |
else | |
echo "File not found: \"$IGNORE\", continuing without the ignore file" | |
fi | |
fi | |
# Count the number of ids, ignore empty lines. | |
TOTAL=$(echo "$ID_LIST" | awk "NF" | wc -l) | |
if [[ $TOTAL -ne 0 ]] | |
then | |
echo "Downloading $TOTAL video(s)..." | |
# Extract audios of the videos using parallel and display a progress bar. | |
echo "$ID_LIST" | parallel --bar extract_audio $OUTPUT | |
# Store the ids if specified | |
if [ -n "$SAVE" ] | |
then | |
echo "$ID_LIST" >> "$SAVE" | |
fi | |
else | |
echo "No videos to download" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment