Coercion is Good

pudge on 2001-11-21T03:56:47

So I have this little MacPerl script that gets the current track info on my MP3 player (SoundJam) using Apple events. I also added some logic so that if SoundJam was not running locally, it would check the other machine in the room, using Apple events via TCP/IP with that remote machine. All fine and good.

The problem: I installed iTunes 2 on a couple of machines, and I figure, hey, iTunes is based on SoundJam, so it should work the same. But they changed it so iTunes 2 returns this data in UTF-16 ("utxt"), instead of regular 8-bit text ("TEXT"). I don't have the requisite Perl modules to convert at this point, but I shouldn't need them, because there are corecion handlers in Apple events that will coerce data from one type to another.

In theory, and according to the docs, it should work fine to just do (in AppleScript):

set songname to name of current track as string

Or in Perl:

my $song = $sj->get($sj->prop(name => of => 'current track'), as => 'string');

But this wasn't working. After trying to work around it (including by just stripping the high byte, which works for my purposes :-), I remembered there was a new development version of AppleScript available (the AppleScript library contains the Apple event code). I installed it, and it worked (as soon as I added a coercion from "utxt" to "TEXT" in the Perl code).

Bah. So I wasted a lot of time, but got it to work.

NP: A Place Of Springs - Phil Keaggy (Beyond Nature)