Skip to content

Instantly share code, notes, and snippets.

@hemanth
Forked from andiandi/youtube.sh
Created July 4, 2012 06:17
Show Gist options
  • Save hemanth/3045688 to your computer and use it in GitHub Desktop.
Save hemanth/3045688 to your computer and use it in GitHub Desktop.
Download and watch youtube videos from the shell. The Script fetches the url from the clipboard, so that you only have to select the url in your browser and start the script. Works great when mapping "xterm -e youtube.sh" to a shortcut, e.g. Meta-Y.
#!/bin/bash
# Download and watch youtube videos from the shell.
# The Script fetches the url from the clipboard,
# so that you only have to select the url in your
# browser and start the script. Works great when
# mapping "xterm -e youtube.sh" to a shortcut, e.g. Meta-Y.
# requires the tools xclip, youtube-dl and mplayer
# it's probably possible to replace xclip with pbpaste on
# Mac OS X (not testet, yet).
videoplayer=mplayer
# read content of primary selection (select with mouse) and clipboard (ctrl+c)
url1=`xclip -o -selection primary`
url2=`xclip -o -selection clipboard`
yt='http://www\.youtube\.com/watch\?v='
# check for valid youtube urls and read url from stdin otherwise
if [[ "$url1" =~ $yt ]]; then
url=$url1
else
if [[ "$url2" =~ $yt ]]; then
url=$url2
else
echo "enter youtube url"
read url
if [[ !( "$url" =~ $yt ) ]]; then
echo "no youtube url found"
exit
fi
fi
fi
# make tempfile
tmpfile=`mktemp`
echo "temfile is: $tmpfile"
echo "youtube url is: $url"
# download youtube video
youtube-dl -b --output "$tmpfile" "$url" > /dev/null &
youtubePID=$!
# start mplayer with a short delay to buffer some data
echo "buffering..."
filesize=0
i=0
while [ $i -lt 20 ] && [ $filesize -lt 200000000 ]; do
sleep 1
let i+=1
filesize=(`du "$tmpfile"`)
filesize=${filesize[0]}
done
# start playing video
$videoplayer "$tmpfile"
# cleanup
kill $youtubePID 2&> /dev/null
rm "$tmpfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment