Refined random selection to work by count, size, or length of songs
}
}
+my %size_exp = (k => 10, m => 20, g => 30, t => 40);
+sub size_expand {
+ my $q = shift;
+ $q =~ /([kmgb])b?$/i;
+ my $s = lc $1;
+ if (exists $size_exp{$s}) {
+ $q <<= $size_exp{$s};
+ }
+ return $q;
+}
+
+sub time_expand {
+ my $time = shift;
+ my @t = reverse split(/:/, $time);
+ warn "More than three segments in time value: $time"
+ if @t > 3;
+
+ my $v = shift @t;
+ my $m = 60;
+ while (@t) {
+ $v += (shift @t) * $m;
+ $m *= 60;
+ }
+ return $v;
+}
+
sub db_add {
my $file = fullpath(shift);
return unless -f $file;
print "\tbitrate\t\t", $r->{'bitrate'}, "kbit\n";
print "\tsamplerate\t", $r->{'samplerate'} / 1000, "kHz\n";
print "\tchannels\t", $r->{'channels'}, "\n";
+ print "\tsize\t\t", -s $file, "\n";
}
if ($ARGV[0] eq 'add') {
}
}
} elsif ($ARGV[0] eq 'random') {
- my $n_files;
- if ($ARGV[1]) {
- $n_files = $ARGV[1];
+ shift;
+ my $method = shift;
+ my $quantity = shift;
+ if ($method eq 'size') {
+ $quantity = size_expand($quantity);
+ } elsif ($method eq 'length') {
+ $quantity = time_expand($quantity);
+ } elsif ($method eq 'all') {
+ ($quantity) = $dbh->selectrow_array(qq{SELECT count(*) FROM tunes});
+ $method = 'count';
+ } elsif ($method eq 'count') {
+ # Do nothing
+ } elsif ($method =~ /^\d+$/) {
+ $quantity = int($method);
+ $method = 'count';
} else {
- ($n_files) = $dbh->selectrow_array(qq{SELECT count(*) FROM tunes});
+ print "Unknown kind of random: $method $quantity\n";
+ exit 1;
}
+ my $n_files;
+
+ if ($method eq 'count') {
+ # This could take a very large amount of memory...
+ my @files = @{$dbh->selectcol_arrayref(qq{SELECT filename FROM tunes})};
+
+ for my $i (1..$quantity) {
+ my $n = int(rand(@files));
+ print scalar splice(@files, $n, 1), "\n";
+ last unless @files;
+ }
+ } elsif ($method eq 'size') {
+ my @files = @{$dbh->selectcol_arrayref(qq{SELECT filename FROM tunes})};
- # This could take a very large amount of memory...
- my @files = @{$dbh->selectcol_arrayref(qq{SELECT filename FROM tunes})};
+ my $size = 0;
+ while ($size < $quantity) {
+ my $n = int(rand(@files));
+ my $file = splice(@files, $n, 1);
+ $size += -s $file;
+ print "$file\n";
+ last unless @files;
+ }
+ } elsif ($method eq 'length') {
+ my @files;
+ my $sth = $dbh->prepare(qq{SELECT filename,length FROM tunes});
+ $sth->execute;
+ while (my $row = $sth->fetchrow_arrayref) {
+ push @files, [@$row];
+ }
- for my $i (1..$n_files) {
- my $n = int(rand(@files));
- print scalar splice(@files, $n, 1), "\n";
- last unless @files;
+ my $length = 0;
+ while ($length < $quantity) {
+ my $n = int(rand(@files));
+ my $file = splice(@files, $n, 1);
+ $length += $file->[1];
+ print "$file->[0]\n";
+ last unless @files;
+ }
}
} elsif ($ARGV[0] eq 'import') {
my $db = $ARGV[1];