How to download Youtube Music and Videos with Python
Tags: python, tutorial, productivity
Published: 2023-02-07 03:57:05

This article will discuss how to easily download music and videos from Youtube using the Python programming language. The reason why we will be using Python is that it is a lightweight, fast and easy tool to use for software development.

We will be using two libraries so as to achieve our aim `argparse` and `pytube` , it can be installed using the python package installer (`pip`).

## Importing the libraries

```python
import argparse
from pytube import YouTube
```

To parse the arguments supplied to the script, we'll use `argparse`, and to download YouTube videos, we'll use `pytube`.

Next, we must provide the folders in which the video and audio should be stored. I do this by using the following constants:

```python
VIDEO_DOWNLOAD_DIR = "../Downloads/videos"
AUDIO_DOWNLOAD_DIR = "..Downloads/audio"
```

## Download function

Let's write a function that takes care of downloading the videos and audio in their respective folders separately.

For audio, we will filter the streams for audio-only content, choose the first one that is available, and download the audio-only stream to the `AUDIO_DOWNLOAD_DIR` directory.

```python
def YoutubeAudioDownload(video_url):
    video = YouTube(video_url)
    audio = video.streams.filter(only_audio = True).first()

    try:
        audio.download(AUDIO_DOWNLOAD_DIR)
    except:
        print("Failed to download audio")

    print("audio was downloaded successfully")
```

For the video, the function takes the URL of the YouTube video and downloads the best/highest resolution available to the `VIDEO_DOWNLOAD_DIR` directory.

```python
def YoutubeVideoDownload(video_url):
    video = YouTube(video_url)
    video = video.streams.get_highest_resolution()

    try:
        video.download(VIDEO_DOWNLOAD_DIR)
    except:
        print("Unable to download video at this time!")

    print("Video downloaded!")
```

These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.

## Main function

The video URL is parsed using argparse in the main function, and an optional audio-only flag is also used. The video's audio will be downloaded if the flag is enabled; by default, both the video and audio are downloaded.

These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.

Let's have a look at the code.

```python
if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-v", "--video", required = True, help = "Youtube video URL")
    ap.add_argument("-a", "--audio", required = False, help = "Audio only", action = argparse.BooleanOptionalAction)
    args = vars(ap.parse_args())

    if args["audio"]:
        YoutubeAudioDownload(args["video"])
    else:
        YoutubeVideoDownload(args["video"])
```

And we are done! 

To test the code out if it actually works, type the following in the terminal.

```python
# for audio
python main.py -a -v "[YouTube video URL]"

# for videos
python main.py -v "[YouTube video URL]"
```

The audio/video directory should have the necessary media downloaded.

## Wrap up

In this article, we discussed how to easily download audio and video from Youtube, using the pytube library. We also used the argparse library to add arguments to the terminal so that we can download the media with shorthand and links to either the audio or video. I personally use this to download songs that I like, and it works perfectly. 

Let’s connect: [Twitter](https://www.twitter.com/Shittu_Olumide_) & [LinkedIn](https://www.linkedin.com/in/olumide-shittu)

You can also check out my [Youtube](https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A) channel.

**Happy coding!** 😊