Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 157 lines (131 sloc) 3.34 KB
#!/usr/bin/env bash
#
# speaker | William Durand <william.durand1@gmail.com>
SYSTEM=`uname`
TTS_LANG=en-us
# The `say` binary
SAY_BIN=say
ESPEAK=espeak
# The `ffmpeg` binary
FFMPEG_BIN=ffmpeg
# Print the help text.
function usage()
{
echo "USAGE:"
echo " $0 [-h] [-d <output directory>] <filename>"
}
# Convert a text to audio file (aiff) using `say`.
#
# $1 - The text to convert.
# $2 - The audio filename.
function to_aiff()
{
echo $1 | $SAY_BIN -o $2
}
# Convert a text to audio file (wav) using `espeak`.
#
# $1 - The text to convert.
# $2 - The audio filename.
function to_wav()
{
$ESPEAK -a 85 -s 135 -p 45 -v $TTS_LANG -b1 -w $2 "$1"
}
# Convert an aiff file to a mp3 file.
#
# $1 - The `aiff` filename.
# $2 - The `mp3` filename.
function to_mp3()
{
$FFMPEG_BIN -y -i $1 -f mp3 $2
rm $1
}
# Read a file, sanitizes its content, and output it.
#
# $1 - The file to read.
function read_content()
{
local content=
local is_code=0
local is_header=0
while read line ; do
if [[ $line =~ ^---$ ]] ; then
if [ "0" -eq "$is_header" ] ; then
is_header=1
else
is_header=0
fi
elif [[ $line =~ ^\`\`\`.*$ ]] ; then
if [ "0" -eq "$is_code" ] ; then
is_code=1
else
is_code=0
fi
elif [[ $line =~ ^\{\%\ highlight\ .+$ ]] ; then
is_code=1
elif [[ $line =~ '{% endhighlight %}' ]] ; then
is_code=0
elif [[ $line =~ ^.+$ ]] ; then
if [ "0" -eq "$is_header" ] && [ "0" -eq "$is_code" ] ; then
content="$content $line"
# Sanitize markdown content
content=`echo "$content" | sed -e 's/[\*_]//g' \
-e 's/\[\(.*\)\](\(.*\))/\1/g' \
-e 's/:[p|D]/./g' \
-e 's/=\{4,\}//g' \
-e 's/#\{2,\}//g' \
-e 's/-\{3,\}//g'`
fi
fi
done < $1
echo $content
}
# $1 - The text to convert
function convert_with_espeak()
{
local content=`read_content $1`
local filename=`echo "$1" | cut -d '.' -f 1`
local wav_file="$filename.wav"
local mp3_file="$filename.mp3"
to_wav "$content" "$wav_file"
to_mp3 "$wav_file" "$mp3_file"
echo $mp3_file
}
# $1 - The file to convert
function convert_with_say()
{
local content=`read_content $1`
local filename=`echo "$1" | cut -d '.' -f 1`
local aiff_file="$filename.aiff"
local mp3_file="$filename.mp3"
to_aiff "$content" "$aiff_file"
to_mp3 "$aiff_file" "$mp3_file"
echo $mp3_file
}
# Convert an input file into a mp3 file.
#
# $1 - The file to convert.
function speaker()
{
echo "Processing: $1"
if [ $SYSTEM == "Linux" ]; then
mp3_file=`convert_with_espeak "$1"`
elif [ $SYSTEM == "Darwin" ]; then
mp3_file=`convert_with_say "$1"`
fi
if [ -d "$2" ] ; then
mv "$mp3_file" "$2/$mp3_file"
echo "=> Done: $!"
else
echo "=> Done: $mp3_file"
fi
}
if [ '0' -eq "$#" ] || [ '-h' == "$1" ] ; then
usage
exit
fi
if [ '3' -eq "$#" ] && [ '-d' == "$1" ] ; then
mkdir -p "$2"
speaker "$3" "$2"
else
speaker "$1"
fi