Jukebox in a single line

If you are like me, who starts starts iTunes with default library and realize you have heard the same song 8 times in the last week, here are two one-line-Jukebox scripts for you. The scripts randomly choose and play songs right from the command line.

Before using the script make sure you have an mp3 player installed. I have installed lightweight mpg123, however you can use any player. I would recommend mplayer for Linux.

While running the scripts, I pass ~/Music folder argument. Change the path to point to folder where you store your mp3s.

First one is in Ruby, and shamelessly inspired by Kevin Baird’s book.

Open a text editor and save this script. I named it shuffle_play.rb. (You need to have ruby installed on your system. Installed on Leopard and most Linux distributions by default.)

#!/usr/bin/env ruby -w
ARGV.sort_by{ rand }.each {|file| system("mpg123 \"#{file}\"")}

To run the jukebox

ruby shuffle_play.rb ~/Music/*.mp3

For the second, I ported above script to bash, which is even more simple and can run on any Linux or OS X. Lets name the script shuffle_play_shell.sh

#!/usr/bin/env bash
n=0;for songs in "$@" ; do song_array[n]=$songs ;((n++)) ; done; for ((i=0;i<$n;i+=1));do number=$RANDOM; let "number %= $n"; `mpg123 "${song_array[number]}"`; done

To run the jukebox

source shuffle_play_shell.sh ~/Music/*.mp3

Update: The second one is not completely random. It will choose n random songs out of n songs. However it does not checks if each song is played at-least once, thus chances of songs getting repeated. Any suggestions?

This entry was posted in Programming and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>