Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/bin/sh
set -x
#Download media + metadata
youtube-dl --write-info-json -x --audio-format mp3 -o "tmp_out.%(ext)s" $1
# Maybe a way to get the file name from previous function
INFO="tmp_out.info.json"
AUDIO="tmp_out.mp3"
echo :: $INFO $AUDIO ::
# Fetch the title
TITLE=$(cat "$INFO" | jq -r .title | sed -e 's/[^A-Za-z0-9._-]/_/g' )
# ^--- Remove all weird character as we want to use it as filename
# We will put all chapter into a directory
mkdir "$TITLE"
# Chapterization
cat "$INFO" |\
jq -r '.chapters[] | .start_time,.end_time-.start_time,.title ' |\
sed -e 's/[^A-Za-z0-9._-]/_/g' |\
xargs -n3 -t -d'\n' sh -c "ffmpeg -y -ss \$0 -i \"$AUDIO\" -to \$1 -codec:a copy -f mp3 \"$TITLE/\$2.mp3\""
#Remove tmp file
rm tmp_out*
@MilesTEG1
Copy link

MilesTEG1 commented Jan 11, 2021

Hello @totetmatt ,
I want to use your script to download audio from a youtube video and splitting with the chapters set on the video.
But, there is an error with xargs on macOS Big Sur :

./youtube_chapter.sh https://www.youtube.com/watch\?v\=IF_0W1cYPYo
+ youtube-dl --write-info-json -x --audio-format mp3 --audio-quality 0 -o 'tmp_out.%(ext)s' 'https://www.youtube.com/watch?v=IF_0W1cYPYo'
[youtube] IF_0W1cYPYo: Downloading webpage
[info] Writing video description metadata as JSON to: tmp_out.info.json
[download] Destination: tmp_out.webm
[download] 100% of 66.84MiB in 00:02
[ffmpeg] Destination: tmp_out.mp3
Deleting original file tmp_out.webm (pass -k to keep)
+ INFO=tmp_out.info.json
+ AUDIO=tmp_out.mp3
+ echo :: tmp_out.info.json tmp_out.mp3 ::
:: tmp_out.info.json tmp_out.mp3 ::
++ cat tmp_out.info.json
++ jq -r .title
++ sed -e 's/[^A-Za-z0-9._-]/_/g'
+ TITLE=Dune_-_Spice_Opera
+ mkdir Dune_-_Spice_Opera
mkdir: Dune_-_Spice_Opera: File exists
+ cat tmp_out.info.json
+ sed -e 's/[^A-Za-z0-9._-]/_/g'
+ jq -r '.chapters[] | .start_time,.end_time-.start_time,.title '
+ xargs -n3 -t '-d\n' sh -c 'ffmpeg -y -ss $0 -i "tmp_out.mp3" -to $1 -codec:a copy  -f mp3  "Dune_-_Spice_Opera/$2.mp3"'
xargs: illegal option -- d
usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]
             [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]
             [-s size] [utility [argument ...]]
+ rm tmp_out.info.json tmp_out.mp3

Is there a workaround to use it on macOS ?

Thanks.

@jeromeludmann
Copy link

jeromeludmann commented Apr 10, 2021

Thank you for this script @totetmatt!

@MilesTEG1, on macOS, you can get GNU xargs by installing:

brew install findutils

Then in the script, use gxargs instead of xargs.
It should work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment