Friday, March 6, 2009

Adding to iTunes via the command line

I recently had the need to add a whole bunch of files to iTunes. I'm a nutty Unix geek, so rather than spending the 10 seconds required to start iTunes, select File->Add To Library, and then select the files, I spent the 30 minutes required to figure out how to do it from the command line, and then the extra 15 minutes to write it up in this blog. But hey, that's what we geeks do ;-).

Actually, this is not as crazy as it sounds, I wanted to automate the whole process of file conversion using Handbrake and then adding to iTunes. In the past, I used iSquint for this, but alas, iSquint is no more. The new version of Handbrake supports conversions from files, instead of only from DVD's.

This is how I did it:
  1. Use HandbrakeCLI to convert the files to MP4 format, using a script along these lines. I found this HandbrakeCLI guide to be very handy. This script is not foolproof - it should check to make sure the file exists before calling HandbrakeCLI, etc., but it shows the concept.

    for i in $*
    do
    echo starting $i at `date`
    base=`basename $i .avi`
    /Applications/HandBrakeCLI -i $i -o $base.mp4 --preset="iPhone & iPod Touch"
    echo ending $i at `date`

    done


  2. Use AppleScript to add it to iTunes, as in this script.

    for i in $*
    do
    if [ -f $i ];
    then
    echo adding file $i
    osascript -e "tell application \"iTunes\" to open POSIX file \"$i\""
    fi
    done

    The trick here is that you need to specify the full path when calling this script, something like this:

    $ add-to-itunes.bash `pwd`/*.mp4

    otherwise the AppleScript will fail:

    29:63: execution error: iTunes got an error: Can’t make some data into the expected type. (-1700)

  3. And that's it! iTunes automatically starts playing the file, this is an option that you can turn off via preferences.

5 comments:

Adam said...

Hi,

Regarding your comment about iTunes will start playing--have you tried "add POSIX file.." that seems to do more of what you (and I) want.

Anyway, thanks for the pointer to open..it helped me move along.

Ari Shamash said...

Hi Adam,

You are absolutely correct, you can use the "add" command instead of "open" to avoid starting to play the file.

I recently started using Python and Appscript (http://appscript.sourceforge.net/) instead of the command line to add content to itunes, works well, as it allows me to set the media type and other attributes while adding the file.

Tobi said...

thanks for posting i use this alot now. but i can't stop itunes from automatically playing this files - its really annoying. i can't find the setting you mentioned in the latest itunes version - any hitns?

Ari Shamash said...

Hi Tobi --

Instead of "open POSIX file" use "add POSIX file" instead, that will add the file without playing it.

The feature I mentioned must have been there in an older version of itunes...

Tobi said...

Thanks, now it is perfect.