Play random files with Ruby
I’ve written a class to play random files, you can define the player path and allowed file extentions. It will search recursively for all readable files, starting from execution from the folder passed as argument or, if miss, from current folder. Tested on a linux box with mplayer.
Usage:
$ ./shuffle
# play recursively all files from current folder
$ ./shuffle /path/to/files
# play recursively all files from specified folder
That’s the source code.
#!/usr/bin/ruby
player = "/usr/local/bin/mplayer"
formats = ["mp3", "ogg", "flv"]
folder = ARGV[0] || ""
class ShufflePlayer
@files
@frx
@player
def initialize(player, formats, folder)
@player = player
gen_regex(formats)
load_files(folder)
end
def play
flag = 1
while flag && @files.length > 0
flag = system("#{@player} -quiet #{@files.delete(@files[rand(Time.now) % @files.length])}")
end
end
private
def load_files(folder)
@files = Dir[folder+'**/*.*'].reject!{|f| f if @frx.match(f).nil? || !File.readable?(f) }
@files.collect!{|f| f.gsub(/['"\-\s\[\]\(\)]/){ |m| "\\"+m }} unless @files.nil?
end
def gen_regex(formats)
@frx = /(#{formats.join('|')})$/
end
end
ShufflePlayer.new(player,formats,folder).play
Security disclaimer: this code is strong insecure, i’ve posted for study purpouses, I’m not responsable if someone use it to attack your system.