Overview

For the longest time, I’ve been converting youtube video to audio using a neat command-line program called pacpl. I’ve written about it in the past and it does what it does pretty well. One downside however is that it only converts video that’s already been downloaded. Although that’s not such a terrible thing, it would be a smoother experience to do both things using one command. Enter Youtube-dl. This is yet another command-line program that not only downloads video content from youtube but also other video platforms. It has the added benefit of being able to extract audio from video. This is what we’ll be going over in this short tutorial. We’re going to write a small bash script that asks us for a youtube link and then extracts the audio content.

What you’ll need

  • Bash terminal
  • youtube-dl

Getting set up

If you don’t have youtube-dl installed, then please do so. There are a number of ways to install it but I’ll be going over how to do it on Debian-based systems i.e Ubuntu, Elementary etc. Head over to the installation page if you want to install it using curl or brew for mac users.

sudo apt install youtube-dl

Updating Youtube-DL

youtube-dl -U

Create a bash file.

Now that we have youtube-dl installed, let’s create a file to store our bash script. You can name it whatever you like.

touch ytdl

Edit bash file

Open up the file using your favorite editor and type the following script. What we’ll be doing is asking the user for a link to download and after the video has been downloaded and converted, we’ll simply ask for another link. If you’re thinking we’ll need a loop for this functionality, then you’re absolutely right.

while true; do
    echo "> Enter video link to extract audio:"
    read input #this stores the user input in a variable called input
    youtube-dl --extract-audio --audio-format mp3 $input
done; 

Make bash file executable

The next thing we’ll want to do after writing our script is to make it executable. This is what essentially turns the file into a program.

chmod a+x ytdl

Run script

Once we’ve made the file executable, we can now run it to test the program.

./ytdl

You will be prompted to enter a link and the program will download the video and extract and save the audio. There’s definitely more ways we can extend this script to add validation for our links for example but this is the basic functionality that we need.