Monday, August 8, 2011

*Listen* to Youtube on linux (legally)

Per the terms of service, you are not supposed to download YouTube videos. However, it does NOT say that you cannot view them in something other than a web browser.  The main problem with youtube is how much garbage/dodginess there is.  Also, most of the time I just want to listen to the music anyway.... what to do?

The answer: use youtube-dl to provide the correct download link, then stream to mplayer and null the video.

  1. Download youtube-dl and put somewhere in your path (such as ~/bin/) and make executable.  If your player breaks, just download the latest version (up within 24 hrs of a youtube site modification) and it should work again.   They have a youtube-dl .deb package in the ubuntu repos, but it is obsoleted pretty fast (for instance 10.04 doesn't work).
  2. make sure mplayer and python are installed: (sudo apt-get install mplayer python)
  3. Use this command:
mplayer -vo null -cookies -cookies-file /tmp/cookie.txt $(youtube-dl -g -f 34 --cookies /tmp/cookie.txt "")

Of course, you will change the video link to be the one you like.  Here is some explanation of what is going on:
  • Youtube requires cookies to be enabled.  We get the video link via youtube-dl and put it into the cookie file.  mplayer is using cookies and reads the url to play from the cookie file.
  • The -g means get the url, and -f changes which file format you are getting the link to (look up youtube codes... current options are 5, 34, 35, 18, 22, 37, 38, 43, 44, 45, 17).  34 is the lowest resolution flv format at 128 kbits/s sound (and I think is standard "360").  18 would give you 96 kbits/s sound.   
  • -vo null means no video output.  Use -fs instead if you want full screen, or nothing for that option if you want regular.
There you have it.  Robust, legal, streaming audio player for youtube.

This also seems to work on short playlists, but not always:

mplayer -vo null -cookies -cookies-file /tmp/cookie.txt $(youtube-dl -g -f 34 --cookies /tmp/cookie.txt "")

Navigate through the tracks with ">" and "<".