Text to iTunes shell script

When I posted my automator workflow for turning text to speech and importing the result into iTunes, I admitted I felt like I was giving up a bit by failing to write a shell script to do this and settling for an Automator workflow.

The primary advantage of a shell script: it makes it easier to ssh into a computer remotely (in my case, my iMac at home, where I keep my iTunes library) and run the script via command line. Yes, you can use the automator command, but any interactivity with Automator still goes through the GUI, which obviously won’t work when you’re connecting remotely to a Mac via the command line. Yes, you can pass variables into the automator command to address this, but…look, I just wanted to do it without Automator, ok? And now I have!

With the exception of mp4tags for setting ID3 tags on the mp4 audio files (which you can get here or by installing the macports package mpeg4ip), this script uses only built-in commands available with OS X 10.5. It takes one argument: a plain text file with the text you want to speechify.

#!/bin/sh

# Set a working directory 
# I use the Trash, but this only makes sense if you have iTunes copying 
# new files into your iTunes folder for you
workdir="~/.Trash"

### give help for empty command
if [ -z "$1" ];
    then
        echo "Speak text file using 'say', set id3 tags and import to iTunes"
        echo "Takes one argument: a plain text file."
        echo ""
        echo "USAGE: "
        echo "  $0 [file]"
        echo ""
        echo "DEPENDENCIES: "
        echo "  mp4tags command line tool"
        echo "     - a part of mpeg4ip. Info: http://mpeg4ip.sourceforge.net"
        echo "     - 'sudo port install mpeg4ip' with macports"
        exit 1
fi

# id3 variables
artistname="Text to Speech"
albumname="Text to Speech"

# the name/trackname for the new file is $trackname
echo 'Name the file/track:'
read trackname

# the file to convert is $thefile:
thefile="$@"

# the new .m4a and .aiff files
aiffile="$workdir"/"$trackname".aiff
m4afile="$workdir"/"$trackname".m4a

# create aiff
echo "Creating aiff file..."
cat "$thefile" | say -o "$aiffile"

# convert m4a
echo "Converting to AAC audio..."
afconvert -v -f "mp4f" -d "aac@22050" -s 0 -q 127 -b 64000 "$aiffile" "$m4afile"

# set id3 tags with mp4tags
echo "Setting id3 tags with mp4tags..."
mp4tags -s "$trackname" -a "$artistname" -A "$albumname" "$m4afile"

# add to itunes
echo "Adding to iTunes..."
osascript <<EOT
set foo to posix file "${m4afile}" as alias
tell application "iTunes" to add foo
EOT

So my normal use of this: ssh to my iMac that holds my iTunes library, open vim, paste in whatever text I want to turn to speech (make sure you set your terminal to UTF-8 if you have problems with garbled characters) and run text2itunes mytextfile.txt. It will prompt you for a track title and then do its work.