Controlling iTunes from PHP 5

  • Posted by Mike Naberezny in PHP

    If you are running PHP 5 on Windows, there is support for COM interfaces built right into the PHP core. The COM support in PHP 5 allows you to automate all kinds of software that expose COM interfaces, such as Microsoft Office. Everyone’s favorite music player, iTunes, also exposes a very nice set of COM interfaces that are easily controlled from PHP 5.

    To get started, instantiate a new COM client to iTunes. If iTunes is not currently running, it will be opened automatically.

    // Instantiate a new COM client to iTunes
    $iTunes = new COM('iTunes.Application');
    

    This creates an object $iTunes which is a client to the IiTunes interface, the top-level interface to the iTunes application. From here you can directly access a number of useful methods and properties for controlling iTunes, or you can access the other interfaces that it provides.

    // Easy Controls
    $iTunes->Play();
    $iTunes->Pause();
    $iTunes->Stop();
    $iTunes->PreviousTrack();
    $iTunes->NextTrack();
    $iTunes->SoundVolume = 50;
    

    To monitor what’s currently playing in iTunes, you can use the CurrentTrack property of IiTunes to return an IITrack.

    // What's playing now?
    $currentTrack = $iTunes->CurrentTrack;
    $trackName = $currentTrack->Name;
    $trackNumber = $currentTrack->TrackNumber;
    $albumName = $currentTrack->Album;
    $artistName = $currentTrack->Artist;
    

    While the capitalization of the methods and properties isn’t the normal way for PHP objects, I’d recommend doing it this way to stay consistent with the naming conventions of the iTunes COM classes. They are actually not case sensitive.

    These examples only scratch the surface of what you can do with the iTunes interfaces. To learn more about controlling iTunes with COM, you can get the complete iTunes SDK from Apple which includes documentation in CHM (Windows Help) format.

    Note: While these examples look like they should work on PHP 4, they consistently caused my PHP 4.3.10 interpreter to crash. COM support was completely rewritten for PHP 5 and all of the examples here were tested under the CLI version of PHP 5.0.3 without any problems. Please note that these examples will most likely not run under a webserver.