Wednesday, January 11, 2006

How to play a random tune in MacOSX?

Here is a little script to play a random tune in MACOSX. I have enjoyed it since years.

Set this script as an executable, and run it interactively (you will need to put a .command extension to run it from the Finder). I use it as an alarm for the morning. How cool is that.

You will need to configure ONLY the path to the directory where all your music files reside. I use Korn Shell (ksh) as a personal preference but this script should work w/o or w/ very slight alterations. Why do I use QuickTime at the end instead of iTunes? Because I wanted to play ONE file only.

To run it from the terminal window type: ./playRandom.command

Your comments are welcome. We can come up with a more sophisticated version.

#!/bin/ksh
# enter here the path to your music directory:
f='/Volumes/yourDisk/yourMusicDirectory'

# temp file:
l='/tmp/musicList.tmp'
if [[ ! -e $f ]]; then
echo Sorry, $f is not accessible.
exit 1
fi

r=$RANDOM
find $f -name *.mp3 > $l # list of mp3 from f root folder
t=`wc -l $l |awk '{print $1}'` # how many titles?
if [[ $t -eq 0 ]]; then
echo Sorry, no title found.
exit 0
fi

echo "Random = $r , nb titles = $t"
# takes modulo:
# remainer of division of random number by number of mp3 files
n=`bc << eof
($r % $t)+ 1
eof
`
echo "number is $n"
c="sed -n '${n},${n}p' $l"
# gets this line number modulo to play
title=`/bin/ksh -c "$c"`
echo "+++++ Playing $title +++++"
open -a "QuickTime Player.app" "$title" &
rm $l

No comments: