Hack:addrandom
From Music Player Daemon Community Wiki
Use this bit of code to randomly add songs to what is currently playing. Anyone know how to adjust for weighted playlists?
- Code
#!/bin/bash
#evildick:04:24:2006
mpddb=/var/lib/mpd/database
addrandom() {
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/temp$$
trap "rm -f $tempfile" 0 1 2 5 15
tempfile1=`tempfile 2>/dev/null` || tempfile1=/tmp/temp1$$
trap "rm -f $tempfile1" 0 1 2 5 15
sed 's/ /^/g' $mpddb > $tempfile
getdbfile="$(cat $tempfile | grep file | cut -c 7-)"
dbfile=($getdbfile)
num_dbfile=${#dbfile[*]}
echo "${dbfile[$((RANDOM%num_dbfile))]}" > $tempfile
sed 's/\^/ /g' $tempfile > $tempfile1
mpc add "$(cat $tempfile1)"
}
addrandom
I made a similar script, the main difference is in how we select the songs (array vs. text file + tools), but I made mine so you can pass an integer argument to it and have it add that number of songs. But I have nothing for weighted playlists.
- Code
#!/bin/bash
# gunnihinn @ 19.11.2007
hjalp ()
{
echo "Usage: addRandom [OPTION]... [INTEGER]..."
echo "Adds INTEGER numer of randomly selected songs"
echo "to the current mpd playlist."
echo " "
echo " -h, --help Display this help"
}
# Make sure the input argument is an integer.
# Set number $num of songs to be added.
if [ $# -eq 0 ]; then
hjalp
exit
elif [ $1 = "--help" -o $1 = "-h" ]; then
hjalp
exit
else
if [ `echo $1 | grep [^0-9]` ]; then
echo "Error: Argument not an integer. Exiting."
exit
else
num=$1
fi
fi
# Get all song file names in database.
# We borrow a file in /tmp
mpc listall > /tmp/songs.tmp
numSongs=`wc -l /tmp/songs.tmp | sed "s/ \/tmp\/songs.tmp//"`
if [ $numSongs -eq 0 ]; then
echo "Error: No songs in database."
rm /tmp/songs.tmp
exit
fi
# Add all songs if $num is too big
if [ $num -gt $numSongs ]; then
num=$numsongs
fi
for (( i = 1; i <= $num; i++ ))
do
songnr=`expr 1 + $RANDOM % $numSongs`
song=`cat /tmp/songs.tmp | head -n $songnr | tail -n 1`
# Don't add the same song twice, fix number of songs
mpc add $song && sed -i "\^$song^d" /tmp/songs.tmp && numSongs=`expr $numSongs - 1`
done
# Make it squeaky clean
rm /tmp/songs.tmp
