Using MPV with Newsboat

I use Newsboat to read RSS feeds including mp3s and YouTube Videos. I want to be able to watch YouTube videos from the command line and not from the browser. The standard suggestion is to create a macro in Newsboat and pass the YouTube url to mpv. MPV then takes the url and plays the video. Here is where I was having issues. The URL you see in your browser for the YouTube video is not actually the URL for the video that gets played on your computer. The URL you see in your browser is the "doorway" to the actual video URLs. For each video there are several URLs, ones that are video only, ones that are audio only, ones that are high quality, and ones that are low quality. I find that sometimes, not always, MPV has trouble finding an URL to play. Sometimes it will work fine, sometimes it will play the audio only URL, and sometimes it cannotnot find a URL to play at all. This problem occurs even with the most up to date youtube.lua file for MPV.

The one program I find that is very good at keeping up with the changes at YouTube is youtube-dl. It is a command line program that lets you download YouTube videos. YouTube-dl can be used to download the desired video and then the video can be watched with MPV. But what if you want to stream the video and not download it. YouTube-dl has a neat little flag -g which gets the video's URLs but doesn't download them. Youtube-dl also has a -f flag which allows the user to specify what format they want. One of the options is best. So if you use youtube-dl -g -f best youtube-dl will send to stdout the URL of the best quality video. This URL MPV can play without any issues.

So here come a bash script to the rescue:

 youtube-dl -g -f best $1 | xargs mpv 

This little script has one argument, the URL of the video's YouTube page. Youtube-dl finds the URL of the best quality video and then it is piped to MPV and the video is played.

To call this from Newsboat you need to create a macro.

 macro m set browser "tsp nbyt %u"; open-in-browser ; set browser "lynx"

The macro sets the browser to the script I created called nbyt, then opens the script while passing the URL to it, and finally sets the browser back to the default. The tsp command allows the script to be run in the background so Newsboat is able to do something else.

One key to keep this all working is to keep youtube-dl updated with youtube-dl -U. YouTube is constantly changing things so youtube-dl must be constantly updated so it continues to work.

As always feel free to use the script at your own risk.

Zettelkasten ID mpvyoutube-2020-05-27-0831