DIY YouTube to MP3 (or MP4) Download

A simple tutorial with Python along with a ready to use Flask webapp

XQ
The Research Nest

--

With the rise of high-speed network connectivity, streaming platforms, and accessibility, downloading stuff locally on our gadgets is a thing of the past. However, if you want to download something on YouTube locally for your personal use — to keep a record or edit something offline, you would probably go to one of those random YouTube downloader websites.

Filled with spam, ads, and whatnot.

Not anymore!

Here’s a simple DIY tutorial and a ready-to-run Google Colab for downloading YouTube videos.

You can run this code locally on your system using Python, too.

I use a similar code for TechFlix in the video summary generation process, where the first step is to extract the audio.

It’s as simple as five lines of code. You don’t even need to have much programming knowledge to run them. Here it goes.

We can use pytube for downloading.

pip install pytube
from pytube import YouTube

def download_youtube_audio(video_url):
video = YouTube(video_url)
audio = video.streams.filter(only_audio=True).first()
actual_filepath = audio.download("./")
return actual_filepath

That’s it!

(If you want to download the video also, you can simply remove the only_audio parameter)

You can run this function by passing a link to the YouTube video (as a string) you want to download. The downloaded video is saved in the same directory as this Python file. In Google Colab, it will download in the working directory.

Example

download_youtube_audio('https://youtu.be/L-SiUKcVe2s?si=e3obzunhWCx_2HIi')

Those who want to use the code and run it directly can make a copy of the Google Colab below. All you need to do is replace the URL with any YouTube video you want to download and run.

The below content is focused on developers who want to do more and build on top of this.

I polished a few things for better use. If you wish to use a more nuanced version (still pretty basic at the time of writing this article), check out this repository on GitHub.

I have added the following:

  1. A Flask web app with a nice minimal UI (this article’s cover image) and API endpoints to make the conversion easy and straightforward.
  2. Added both video and audio download options.
  3. Some basic exception handling, checks, and validations.
  4. Logging for better debugging in case of any issues.
  5. Dark mode, because why not?

Go through the readme file for all the details you need.

Accepting PRs, feature requests, ideas, and so forth. Feel free to engage with the repository on GitHub.

--

--

XQ
The Research Nest

Exploring Tech, Life, and Careers Through Content 🚀