randomising tracks: scripting question

Joseph Olatt joji at eskimo.com
Tue Jan 4 04:34:16 UTC 2011


On Sun, Dec 26, 2010 at 05:09:30PM +0000, Frank Shute wrote:
> 
> I generally play my tracks of an album like so:
> 
> for track in $(cat trombone_shorty-backatown.m3u); do
> mplayer $track
> done
> 
> They then play in the correct order.
> 
> How would I go about randomising the order of play using
> sh (preferably) or perl?
> 
> Sorry for the OT posting but I thought a brainteaser might clear the
> fog caused by excessive Xmas indulgence ;)
> 
> 
> Regards,
> 
> -- 
> 
>  Frank
> 
>  Contact info: http://www.shute.org.uk/misc/contact.html
> 
> 

A little while back I wrote a perl script to randomly pick mp3, 
ogg, flac files from any directory specified as arg 1 and play them
using mplayer. 

I categorize my genres by directory and with this perl script I can
randomly play songs from any directory.

If the script is invoked without any arguments, then it will play songs
from the default hard-coded directory defined by $SONG_DIR.

Don't know if this would be useful to you (or someone else). 


#!/usr/bin/perl -w

use strict;

my $SONG_DIR = "/home/joji/songs/good";

if ($#ARGV == 0)
{
    $SONG_DIR = $ARGV[0];
}

my %played = ();
my $rand;
my $dh;
my @song_list;


opendir($dh, $SONG_DIR);
@song_list = readdir($dh);
closedir($dh);

my $count = $#song_list;

# Perl counts from zero. If there is one item, Perl will say 0.
# So to get the real count, we have to increment by 1.
$count++;

chdir($SONG_DIR);

while ((keys %played) < $count)
{
	while (1)
	{
        	$rand = int(rand($count));
        	if (! $played{$rand})
        	{
        		$played{$rand} = 1;
        		last;
        	}

		if ((keys %played) >= $count)
		{
			last;
		}
	}

    if ($song_list[$rand] eq "." || $song_list[$rand] eq "..")
    {
        ;
    }
    else
    {
        print "Playing song # " . $rand . " [" . $song_list[$rand] . "]\n";
        `mplayer \"$song_list[$rand]\"`;
    }

}

exit(0);


More information about the freebsd-questions mailing list