Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 3 Jan 2011 20:23:38 -0800
From:      Joseph Olatt <joji@eskimo.com>
To:        Frank Shute <frank@shute.org.uk>
Cc:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Re: randomising tracks: scripting question
Message-ID:  <20110104042338.GA29930@shell.eskimo.com>
In-Reply-To: <20101226170930.GA68817@orange.esperance-linux.co.uk>
References:  <20101226170930.GA68817@orange.esperance-linux.co.uk>

next in thread | previous in thread | raw e-mail | index | archive | help
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);



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20110104042338.GA29930>