#!/bin/bash

# speaks the time using sampled audio files.
# can be played at speeds to alter the voice.
# if xmms is playing pause while speaking the time.

# timeis 08/02 rednhut

# more information can be found at http://www.jumpstation.co.uk/scripts/talkingclock/
# I had written time2speak.sh that used flite to speak the time, but this is more personal.

installDir=${0%/*}
if [ $installDir = $0 ]; then
  installDir="."
fi
dataDir="data"
if [ ! -e $installDir"/"$dataDir"/0.wav" ]; then
  dataDir=""
  if [ ! -e $installDir"/"$dataDir"/0.wav" ]; then
    echo "no data files found in $installDir/$dataDir"
    exit 1
  fi
fi

# if set to "Y" then change the voice (speed) each time the script is called.
voicechange="Y"

# the basic WAV files I recorded are 8000Hz mono, if you use something else then you may have to change this
basicrate=8000

# these two lines ensure I am more likely to get a faster rather than slower voice
biased=2000
basicrate=$((basicrate + $biased))

# if voicechange mode is set then use this as the min/max variration
variance=4000
change=$(($RANDOM%$((variance * 2)) ))

args=$1

# no processing required
function sayHours() {
  wavplay $1.wav
}

# no processing required
function sayAMPM() {
  wavplay $1.wav
}

# have to split the number and deal with 00-09,10-19, then 20-59
function sayMins() {
  # the first "1" is the variable name, the next number is the starting character and the last is the length of the string to be returned
  tens=${1:0:1}
  units=${1:1:1}
  # check length
  if [ ${#units} = 0   ]; then
    units=$tens
    tens="0"
  fi
  if [ $tens -lt 1 ]; then
    wavplay $tens.wav
    wavplay $units.wav
  elif [ $tens -lt 2 ]; then
    wavplay $1.wav
  else
    tens=$tens"0"
    wavplay $tens.wav
    if [ $units -gt 0 ]; then
      wavplay $units.wav
    fi
  fi
}

# use the sox play command with required parameters.
function wavplay() {
  rate=""
  effect=""
  if [ "$voicechange" = "Y" ]; then
    rate="--rate="$(($((basicrate - variance)) + $change ))
    effect=$args
  fi
#effects are complex, see "man sox" or try one the following and read the error messages
# avg, band, chorus, copy, cut,
# deemph, echo, echos, flanger, highp, lowp, map, mask, phaser, pick,
# polyphase, rate, repeat, resample, reverb, reverse, split, stat, vibro
#  echo "play $rate --file=$1 $effect"
  play $rate --file=$installDir"/"$dataDir"/"$1 $effect
  # if you do not like the way the play command outputs lots of information just add >/dev/null on then end.
}

# the double ampersands mean the following command will only be executed if the first returned true.
# in this case which only returns true is xmms is found in the path.
which xmms >/dev/null && xmms --play-pause
hours=`date +"%-l"`
sayHours $hours
mins=`date +"%-M"` 
sayMins $mins
ampm=`date +"%-P"` 
sayAMPM $ampm
which xmms >/dev/null && xmms --play-pause

