Search code examples
bashffmpegyoutube-dl

Bash: bash script to download trimmed mp3 from youtube url


I would like to download the initially x seconds trimmed mp3 from a video url of youtube.
I found that youtube-dl can download the video from youtube to local machine. But, when I looked at the man pages of youtube-dl, I could not find any trim options.

So I tried to use the ffmpeg to trim downloaded mp3 file.
Instead of doing this is two steps, I like to write one bash script which does the same thing.
My attempt is given below.

However, I was stuck at one place:
"HOW TO GET THE VARIABLE NAME OF OUTPUT MP3 FILE FROM YOUTUBE-DL?"
The script is given below:

# trim initial x seconds of mp3 file
# e.g. mytrim https://www.youtube.com/watch?v=dD5RgCf1hrI 30
function mytrim() {
    youtube-dl --extract-audio --embed-thumbnail --audio-format mp3 -o "%(title)s.%(ext)s" $1
    ffmpeg -ss $2 -i $OUTPUT_MP3 -acodec copy -y temp.mp3
    mv temp.mp3 $OUTPUT_MP3
    }

How to get the variable value $OUTPUT_MP3?
echo "%(title)s.%(ext)s" gives the verbatim output, does not give the output filename.

How could we make the script work?

The help will be appreciated.


Solution

  • youtube-dl supports a --get-filename option, that doesn't actually download anything, but gives the calculated filename on the stdout.

    mytrim() {
        local downloaded_file
        youtube-dl --extract-audio --embed-thumbnail --audio-format mp3 -o "%(title)s.%(ext)s" $1
        downloaded_file=$(youtube-dl --get-filename --extract-audio --embed-thumbnail --audio-format mp3 -o "%(title)s.%(ext)s" $1)
        ffmpeg -ss $2 -i "${downloaded_file}" -acodec copy -y temp.mp3
        mv temp.mp3 "${downloaded_file}"
    }