Skip to content

Instantly share code, notes, and snippets.

@arpanpal010
Last active May 18, 2016 17:02
Show Gist options
  • Save arpanpal010/b4486a7bbf95a45e960369d2a7898664 to your computer and use it in GitHub Desktop.
Save arpanpal010/b4486a7bbf95a45e960369d2a7898664 to your computer and use it in GitHub Desktop.
Youtube player for raspberry pi. Using pip version of Youtube-DL and omxplayer that comes default in Raspbian.
#!/bin/bash
# youtube url player for raspberry pi,
# ------------------------------------------------------------------
ytdlCmd="youtube-dl";
ytdlArgs="-f 140 --prefer-ffmpeg -g"; # 141 - 256k audio, 140 - 128k audio, 22 - best quality available
playerCmd="omxplayer";
playerArgs="--vol -300";
cacheFile="$HOME/.ytdlCache";
# required
# ------------------------------------------------------------------
if [ "$(which $ytdlCmd && echo 1 || echo 0)" = 0 ];
then
echo "Need to have $ytdlCmd in path.";
exit 1;
fi;
if [ "$(which $playerCmd && echo 1 || echo 0)" = 0 ];
then
echo "Need to have $playerCmd in path.";
exit 1;
fi;
# functions
# ------------------------------------------------------------------
getPlayableUrl ()
{
[[ -z "$1" ]] && exit;
echo "$($ytdlCmd $ytdlArgs "$1")";
}
playFile ()
{
[[ -z "$1" ]] && exit;
$playerCmd $playerArgs "$1";
echo "Done Playing";
}
writeInfo ()
{
local url="$1";
local murl;
[[ -z "$2" ]] && murl="$(getPlayableUrl $url)" || murl="$2";
echo;
echo "Source URL : $url";
echo "Playing URL : $murl";
echo;
echo "CMD: grep -q -e '$url' $cacheFile && echo 1 || echo 0";
echo "RES: $(grep -q -e '$url' $cacheFile && echo 1 || echo 0)";
if [ "$(grep -q -e '$url' $cacheFile && echo 1 || echo 0)" = 0 ];
then
echo;
echo "Writing to file";
echo "<ytUrl>$url</ytUrl><pUrl>$murl</pUrl>" >> $cacheFile;
echo "Done.";
echo;
else
echo;
echo "Not writing to file";
echo "Link exists in cache.";
echo;
fi;
}
ytPlay ()
{
local url="$1";
local murl="$(getPlayableUrl "$url")";
writeInfo "$url" "$murl";
playFile "$murl";
}
lsLinks ()
{
if [ -e "$cacheFile" ];
then
grep -io -e '<ytUrl>.*</ytUrl>' $cacheFile | sed -e 's_[<|</]ytUrl>__g' | sed -e 's_<$__g' | sort | uniq;
else
echo "No cache found at path: $cacheFile"
exit 1;
fi;
}
ytPlayRandomCached ()
{
if [ -e "$cacheFile" ];
then
local url="$(lsLinks | shuf -n 1)";
echo "Playing Url: $url";
ytPlay "$url";
else
echo "No cache found at path: $cacheFile"
exit 1;
fi;
}
# cli
# ------------------------------------------------------------------
cli ()
{
case "$1" in
"r") ytPlayRandomCached; exit;
;;
"w") shift; writeInfo "$@"; exit;
;;
"rl") while true; do ytPlayRandomCached; done;
;;
"ls") lsLinks;
;;
*) ytPlay "$@";
;;
esac
}
# if not sourcing, run
# ------------------------------------------------------------------
[[ "$0" == "$BASH_SOURCE" ]] && cli "$@";
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment