#!/bin/bash
# asterisk-wav2mp3 - create stereo mp3 out of two mono wav-files
# source files will be deleted 
#
# 2010-02-28 Nonoo http://www.nonoo.hu/
# 2005-05-23 dietmar zlabinger http://www.zlabinger.at/asterisk

# location of SOX
# (set according to your system settings, eg. /usr/bin)
SOX=/usr/bin/sox
# lame is only required when sox does not support liblame
LAME=/usr/local/bin/lame


# command line variables
LEFT="$1"
RIGHT="$2"
OUTFILENAME="`basename \"$3\"`"
OUTDIRNAME="`dirname \"$3\"`"
EXTENSION=${OUTFILENAME##*.}
OUT="$OUTDIRNAME/${OUTFILENAME%.*}"

# test if input files exist
test ! -r $LEFT && exit 21
test ! -r $RIGHT && exit 22

# convert mono to stereo, adjust balance to -1/1
# left channel
$SOX $LEFT $LEFT-tmp.wav remix 1 0 norm
# right channel
$SOX $RIGHT $RIGHT-tmp.wav remix 0 1 norm

# combine and compress
# this requires sox to be built with mp3-support.
# To see if there is support for Mp3 run sox -h and
# look for it under the list of supported file formats as "mp3".
#$SOX -m -v 1 $LEFT-tmp.wav -v 1 $RIGHT-tmp.wav $OUT.mp3

# in case an old version of sox is used, encoding
# can be done afterwards 
$SOX -m $LEFT-tmp.wav $RIGHT-tmp.wav $OUT.wav
$LAME -S -V7 -B24 $OUT.wav $OUT.mp3

# remove temporary files 
test -w $LEFT-tmp.wav && rm $LEFT-tmp.wav
test -w $RIGHT-tmp.wav && rm $RIGHT-tmp.wav
test -w $OUT.wav && rm $OUT.wav

# remove input files if successful
test -r $OUT.mp3 && rm $LEFT $RIGHT
