Previously I published a script that selected a random audio file (or any file). However it assumed that the folder where you have your files is exclusively filled with audio file types. As a DJ I save mixes to a folder along with text and HTML files that hold the track list. It was getting a little laborious having to re-trigger the script over and over until I hit an actual audio file. So I wrote a script that actually checks the file MIME type

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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/bash
IFS=$'\n'
count=0
dir=$(pwd)
cache=.play-random-cache-$(echo "$dir" | tr / -)
BLUE='\033[0;34m'
NC='\033[0m'
echo -e "\U1F3A7${BLUE}Play Random Audio File${NC}, v1.0, by Michael Z Freeman, 2022, http://michaelzfreeman.org"
if test -f "$cache"; then
    echo
    echo -e "\U1F477Retrieving audio and video files from cache file..."
    readarray -t files < "$cache"
else
echo
echo -e "\U1F50EScanning for audio and video files in current directory (result will be cached) ..."
listall=`ls -dD *` # Read in all files but not directory contents.
files=($listall) # Read into array variable.
for i in "${files[@]}"
do
    echo Current file @ index $count: "$i"
    check=`mimetype -b "$i" | grep -e audio/ -e video/`
    echo Mime type: $check
    if [ -z "$check" ];
    then
        unset files[$count] # Remove non audio or video file from array
    fi
    count=`expr $count + 1`;
done
echo
echo -e "\U1F477Writing cache..."
for i in "${files[@]}"
do
    touch "$cache"
    echo "$i" >> "$cache"
done
fi
echo
echo -e "\U1F477Generating random choice from scanned audio and video files..."
num_files=${#files[*]} # Count how many elements.
num_files=`expr $num_files - 1`;
choice="${files[$((RANDOM%num_files))]}"
echo
echo -e "\U1F50APlaying '$choice'..."
echo
mpv --audio-display=no --cover-art-auto=no "$choice"

With added colour and emoji’s for humanity factor 100% 🤱!

The script will cache the files it analyses so that next time, especially with large folders, response will be almost instantaneous. Of course if you add more files you will have to delete the cache file (it starts with “.play-random-cache“).

Enjoy !

799 views

Leave a Reply

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