It amazing what a bit of randomness can extract from hard drive “lost” zones  🙂

These scripts are probably not the ultimate in Linux scripting elegance and may even have bugs in them that need fixing, but they do work well enough on my machine.

file=
num_files=
choice=
IFS=$'\n'
Files=`ls -D /home/mzf/MZF_Docs/Docs_on_Fifth_Element/Forge/Compressor` 

file=($Files)                # Read into array variable.

num_files=${#file[*]}        # Count how many elements.

choice=${file[$((RANDOM%num_files))]}
echo $choice

mplayer -volume $1 /home/mzf/MZF_Docs/Docs_on_Fifth_Element/Forge/Compressor/$choice 

exit

Usage example …

$ ./play-random-sample.sh 80

 

The number is the volume level.

The script was written for a single directory full MP3 and WAV samples. As I found out, it does not work too well for anything bigger than that – like a directory hierarchy full of various music albums. So I did a bit of rewriting …

file=
num_files=
choice=
IFS=$'\n'
dir=/media/mzf/fifth-element/Music
Files=`find $dir -type f`

file=($Files)                # Read into array variable.

num_files=${#file[*]}        # Count how many elements.

choice=${file[$((RANDOM%num_files))]}
echo $choice

mplayer -volume $1 "$choice"

exit

The script does not check the file type so if you have pictures and so forth along with your audio files it might try to play those. If so, just run it again.

$ ./play-random-track.sh 80

I’ll return later with a version that can show a random image.3,506 views

Spread the love

One thought on “Linux CLI (Bash) – Play Random Audio File, Music Track or Display Random Image”

Leave a Reply

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