Playing a YouTube video on your XBMC Media Center from the CLI

I’m regularly sitting in front of my TV with my laptop, surfing and chatting; many YouTube links pass on IRC or while browsing forums and such. Watching these videos would be a lot nicer on the TV than on the small laptop screen with abysmal speakers, but using the XBMC YouTube Plugin I would have to look for the clip, entering its details again. On my Android phone, I have installed the Yatse XBMC Remote app, which provides a “Play on XBMC” option when opening a Youtube video. For Firefox, Chrome and Opera, there are add-ons that can send a YouTube clip URL to XBMC as well.

However, I’m more of a command-line person, so I decided to conjure up a little bash script opening up a YouTube movie on my TV. From one of the Chrome plugins, I borrowed the regex to parse out the movie ID.

#!/bin/bash

## YouTube XBMC Script 1.0
## (c) 2013, Tom Laermans - http://tom.laermans.net
##
## This script is released into the public domain.

## Configure your XBMC RPC details here

XBMC_HOST=xbmc
XBMC_PORT=8080
XBMC_USER=xbmc
XBMC_PASS=xbmc

## Don't touch anything under here

REGEX="^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*"

ID=$1

if [ "$ID" == "" ];
then
  echo "Syntax $0 <id|url>"
  exit
fi

if [[ $ID =~ $REGEX ]]; then
  ID=${BASH_REMATCH[7]}
fi

function xbmc_req {
  curl -s -i -X POST --header "Content-Type: application/json" -d "$1" http://$XBMC_USER:$XBMC_PASS@$XBMC_HOST:$XBMC_PORT/jsonrpc >/dev/null
}

echo -n "Opening video id $ID on $XBMC_HOST ..."
xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Clear", "params":{"playlistid":1}, "id": 1}';
xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Add", "params":{"playlistid":1, "item" :{ "file" : "plugin://plugin.video.youtube/?action=play_video&videoid='$ID'"}}, "id" : 1}';
xbmc_req '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":{"playlistid":1, "position" : 0}}, "id": 1}';
echo " done."

Using this is as easy as passing either the complete YouTube URL or just the movie ID to it as a parameter. Remember to quote or escape correctly if there are ampersands in the URL, or you’ll be starting a number of background processes in your shell.

Would be nice to have the TV switch to the HTPC input via CEC, but unfortunately I can’t see anything related to that in XBMC’s current API.

Writing informative technical how-to documentation takes time, dedication and knowledge. Should my blog series have helped you in getting things working the way you want them to, or configure certain software step by step, feel free to tip me via PayPal (paypal@powersource.cx) or the Flattr button. Thanks!