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.

Tip: Double click on code for easy copy.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
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 …

Tip: Double click on code for easy copy.
1
$ ./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 …

Tip: Double click on code for easy copy.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
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.

Tip: Double click on code for easy copy.
1
$ ./play-random-track.sh 80

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

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 *