Now-playing script

This script uses the KDE DCOP and Amarok to find the path of the currently playing media file. It makes a symbolic link to this file in a chosen location — in my case, on a web server. Then anyone can hear what I’m currently listening to. To reduce bandwith consumption, it also converts FLAC files to OGG files.

You can download the nowplaying script. It requires Zsh to run, but it would not be difficult to convert it to Bash etc.

#!/bin/zsh
#
# Matthew Blissett, 2007-08-11
#
# Script/daemon to update a symlink to point to the currently playing file 
# in Amarok
#
# Improvements needed:
# – What if Amarok isn’t running?
# – Or isn’t playing anything?
# – Or I press “next track” etc?
#

dir="/home/matt/music/.nowplaying"
recodedir="$dir/recode"
umask 0072

while :; do
	echo -n $(date)
	now=$(dcop amarok player path)
	if [[ "$now:e" == "flac" ]]; then
		echo -n "; FLAC"
		# Check if we have a recoding of the file already
		if [[ -e "$recodedir/$now:t:r.ogg" ]]; then
			echo -n "; already converted to OGG"
		else
			echo -n "; converting to OGG..."
			mkdir -p $recodedir
			nice -n 8 oggenc --quiet --quality 3 --output "$recodedir/$now:t:r.ogg" "$now"
			echo -n " done"
		fi
		target="$recodedir/$now:t:r.ogg"
	else
		if [[ "$now:e" == "mp3" ]]; then
			echo -n "; MP3"
			target="$now"
		else
			if [[ "$now:e" == "ogg" ]]; then
				echo -n "; OGG"
				target="$now"
			fi
		fi
	fi
	echo "; $target:t"
	rm -f $dir/now.*
	ln -sf "$target" $dir/now.$target:e
	echo "$target:t" >! $dir/filename

	totalTime=$(dcop amarok player totalTime)
	currentTime=$(dcop amarok player currentTime)

	if [[ "$currentTime" != "" ]]; then

	    totalSecs=$(( ${totalTime##[0-9]*:} + $(( ${totalTime%%:[0-9]*} * 60 )) ))
	    currentSecs=$(( ${currentTime##[0-9]*:} + $(( ${currentTime%%:[0-9]*} * 60 )) ))
	    
	    remain=$(( $totalSecs - $currentSecs ))
	    
	    echo "${remain}s remaining."

	    sleep $(( $remain + 12 ))
	else
	    echo "Waiting 60s"
	    sleep 60
	fi
done