ru Русский

Reticularium

NETWORKS PLACE

If you (like me) use mplayer to play music, you might want to make it possible to play songs in random order. Here is a simple script for this:

#!/bin/bash

tempfile=/tmp/randplay-$$
touch $tempfile
trap 'rm -f $tempfile; exit' 0
trap 'rm -f $tempfile; exit' 3
trap 'rm -f $tempfile; exit' 15

songsdir="${1}"
# Remove the finding playlist condition below if you want the list of files to be regenerated each time
# you run the script. This is useful if the content is changing often, but delays the script startup.
# You can also simply remove file m.playlist from the folder if its content changes. 
if [ -f "${songsdir}/m.playlist" ]
then
  echo "Playlist found!"
else
  n=1
  OFS=$IFS
  IFS='
'
  for song in `ls "${songsdir}"`
  do 
    echo "$n ${song}" >> "${songsdir}/m.playlist"
    n=`expr $n + 1`
  done
  IFS=$OFS
fi
songstotal=`cat "${songsdir}/m.playlist" | wc -l`
while true
do
  echo ">>> `cat ${tempfile}|wc -l`"
  sleep 1
  a=$RANDOM
  songsnumber=`expr $a - $a / $songstotal \* $songstotal`
  [ `cat ${tempfile} | grep -c ^${songsnumber}$` -gt 0 ] && echo "Skipping `grep "^$songsnumber" "${songsdir}/m.playlist" | sed "s|^$songsnumber ||"`" && continue
  echo ${songsnumber} >> ${tempfile}
  songname=`grep "^$songsnumber" "${songsdir}/m.playlist" | sed "s|^$songsnumber ||"`
  mplayer -quiet "${songsdir}/${songname}"
  [ $? -ne 0 ] && exit 0
done

The syntax is simple:
<script name> <folder>
Use ESC-ESC or PgUp to skip, Ctrl-C to stop.