about // doc

How to Download Youtube Media Files

Created: Nov, 2016

There are many musicians playing amazing pieces on Youtube, and here is my way to grab the video and audio for offline access with a handy Python tool called youtube-dl.

First, install youtube-dl with pip:

virtualenv pyenv
source pyenv/Scripts/activate  # this may be different on different platforms
pip install --upgrade pip
pip install youtube-dl

To extract the audio, one also needs to install ffmpeg utilities.

  • On Windows, download it from here. The statically linked binaries will be convenient. Add the “bin” path to system path.

  • On Mac, install Homebrew, and install ffmpeg from there

brew install ffmpeg

At last, use youtube-dl as follows

youtube-dl -x -k https://www.youtube.com/watch?v=MZuSaudKc68

This will grab all available versions of videos, and extract the audio by the end.

The flag “-k” will save the the intermediate audio and video files before merging via ffmpeg. The audio files were not always in mp3 format (e.g., opus, webm etc.). The following ffmpeg command can convert them to mp3 format (ref here):

ffmpeg -i "input.webm" -vn -ab 192k -ar 44100 -y "output.mp3"

A convenient BASH function for this purpose will be

function convertToMp3()
{
    bit_rate="192k"  # target bit rate
    sample_rate="44100"  # target sample rate

    basefilename=$(basename "$1")  # string off path
    extension="${basefilename##*.}"
    filename="${basefilename%.*}"
    echo "Input file: $basefilename"

    echo "Convert to mp3 with sampling rate of $sample_rate pbs"
    ffmpeg -i "$1" -vn -ab $bit_rate -ar $sample_rate -y "${filename}.mp3"
}

To use it:

convertToMp3 myaudio.webm

And there will be myaudio.mp3 generated in the same folder.

comments powered by Disqus