Thursday, September 26, 2013

Extract audio track from a youtube video

Youtube is a great source for watching videos or listening to music on-line via their website. But if you want to download the video or audio to your computer, you need some special tool, and you need to know the URL for the youtube video you wish to download.

One such tool is youtube-dl, which is a python script. Unfortunately, youtube-dl is not pre-packaged with Debian Wheezy.

I downloaded the script directly from this web page:

$ sudo curl https://yt-dl.org/downloads/2013.09.24.2/youtube-dl -o /usr/local/bin/youtube-dl
$ sudo chmod a+x /usr/local/bin/youtube-dl

The syntax of youtube-dl is quite straight-forward.

To download the complete youtube video (with the soundtrack), just provide the URL of the video as a single argument.

$ youtube-dl http://www.youtube.com/watch?v=O-xlvalecI8 
[youtube] Setting language
[youtube] O-xlvalecI8: Downloading video webpage
[youtube] O-xlvalecI8: Downloading video info webpage
[youtube] O-xlvalecI8: Extracting video information
[youtube] O-xlvalecI8: Encrypted signatures detected.
[youtube] O-xlvalecI8: Downloading js player vflUKrNpT
[download] Destination: Give me oil in my lamp-O-xlvalecI8.flv
[download] 100% of 11.73MiB in 00:43

This creates a Flash Video (.flv) file in your local hard drive. To watch the video off-line, open the .flv file with a media player application such as VLC or Totem.

If it is just the sound track that you want, not the complete video, you can still use youtube-dl. However, to do audio extraction, youtube-dl requires 2 extra programs to be installed. Namely, it requires ffmpeg or avconv, and ffprobe or avprobe.

On my Debian Wheezy system, I installed avconv and avprobe by simply installing this package:

$ apt-get install libav-tools

Finally, you can run youtube-dl like this to extract the audio track only:

$ youtube-dl --extract-audio --audio-format mp3   http://www.youtube.com/watch?v=O-xlvalecI8 
[youtube] Setting language
[youtube] O-xlvalecI8: Downloading video webpage
[youtube] O-xlvalecI8: Downloading video info webpage
[youtube] O-xlvalecI8: Extracting video information
[download] Destination: Give me oil in my lamp-O-xlvalecI8.flv
[download] 100% of 11.73MiB in 00:32
[avconv] Destination: Give me oil in my lamp-O-xlvalecI8.mp3
Deleting original file Give me oil in my lamp-O-xlvalecI8.flv (pass -k to keep)
The --audio-format parameter lets you specify the output audio format. The above command generates a mp3 file on your local hard drive. Besides mp3, you can specify other audio formats such as wav. For detailed help about the parameters, run:
$ youtube-dl --help