TweetFollow Us on Twitter

Studio 54

Volume Number: 19 (2003)
Issue Number: 6
Column Tag: QuickTime

Studio 54

Developing QuickTime Applications with AppleScript Studio

by Tim Monroe


In two previous articles ("The Cocoanuts" in MacTech, December 2002 and "Animal Crackers", January 2003), we took a look at developing QuickTime applications using Cocoa. Cocoa is a set of frameworks for applications that run on Mac OS X; it provides a large set of components, or classes, that we can use to build applications or other software modules. These classes handle basic tasks like event processing, memory management, and data manipulation, as well as higher-level tasks like displaying and managing the graphical user interface of an application.

In those earlier articles, we used the Objective-C language to access the various Cocoa frameworks we employed in our sample application. It's possible, however, to use other languages as well. Cocoa supports development using Java and, more recently, AppleScript. The support for AppleScript is provided by AppleScript Studio, a development environment from Apple that we can use to create Mac OS X applications that access Cocoa's classes and perform other tasks using the AppleScript scripting language. These are called AppleScript Studio applications.

In this article, we're going to see how build an AppleScript Studio application that can open and play QuickTime movies. Because it's built on top of Cocoa, our sample application (called ScripTeez) will conform to the Aqua user interface guidelines and will exhibit the behaviors typical of Cocoa applications. And because it's programmed using AppleScript, it should be simpler to write than our sample Objective-C application, MooVeez.

It turns out, however, that the vocabulary provided by AppleScript Studio for controlling the Cocoa QuickTime classes (NSMovie and NSMovieView) is currently fairly limited. Even a task as simple as resizing a window so that it fits the natural dimensions of a movie will require us to go beyond AppleScript and employ a little Objective-C. That's the bad news. The good news is that it's extremely easy to call Objective-C code from our AppleScript code. We'll be able to weave the two languages together into a seamless whole that handles QuickTime movies quite nicely.

Because we'll need to resort to Objective-C for part of our programming, it would probably be good if you were already familiar with at least the first article mentioned above ("The Cocoanuts"). This would also be good because AppleScript Studio uses the same software development tools (Project Builder and Interface Builder) that we encountered in that article. I'll step through the process of building ScripTeez as gradually as possible, but I'll try not to repeat very much of the information found in those two earlier articles on Cocoa and QuickTime.

We'll begin this article by taking a brief look at AppleScript. The AppleScript we need for this article is so simple that you can pick it up as we go along, even if you've never worked directly with AppleScript before. Then I want to take a quick look at how we handle Apple events in our Carbon sample QuickTime application, QTShell; Apple events are the underlying mechanism by which scripts are able to control other applications, and it's useful to see how QTShell handles them. Also I want to take a quick look at some of the scripting support offered by the QuickTime Player application.

We'll spend most of our time learning how to create an AppleScript Studio application that can open a single window that contains a QuickTime movie. You may notice that I've changed the goal here slightly vis-a-vis the earlier articles in this mini-series on QuickTime development environments. In previous articles, we set ourselves the task of developing multi-document QuickTime applications -- that is, applications that allow the user to open several QuickTime movies in windows on the screen, manipulate them in all the standard ways, and possibly also save any edited movies. In this article, our sample application ScripTeez will allow the user to open just one movie file; more importantly, although ScripTeez supports editing operations, it does not allow the user to save any edited movies back out into their movie files. The reason for this departure is simply that the limited vocabulary currently provided by AppleScript Studio for manipulating QuickTime movies does not provide an easy way to save edited movies. To do this, we'd need to resort to more Objective-C, and we've already seen how to do that in the earlier articles on QuickTime and Cocoa. Here I want to focus on what's distinctive about AppleScript Studio from a QuickTime programmer's point of view, which of course is the ability to open and manipulate QuickTime movies using the AppleScript language.

AppleScript Overview

AppleScript is an English-like language used to control the actions of computers and applications. It was introduced way back in Mac OS System 7.5 and has been part of the Macintosh landscape ever since. The primary appeal of AppleScript is its ability to automate workflow -- that is, to encapsulate a predefined series of steps involving one or more applications. These steps could be accomplished with the applications directly (using the mouse and keyboard) but often at the risk of tedium and error. Suppose, for instance, that we've got a large number of QuickTime movie files that need to be hinted so that they can be streamed across the Internet. We could open each file individually in QuickTime Player and select the appropriate menu items to add hint tracks to the movie; it would be far better, however, to construct a script that accomplishes this task automatically when we drop the movie files onto the script file.

Writing Scripts

A script is a sequence of lines of text (usually contained in a file) that can be executed. Here is a simple one-line script:

tell application "QTShell" to open the file ""

This line of script will launch the application QTShell (if it's not already running) and instruct it to open the specified file. Interestingly, this line of script does not cause QTShell to become the frontmost application. If we want that to happen, we need to explicitly activate QTShell, like this:

tell application "QTShell" to open the file ""
tell application "QTShell" to activate

And we can simplify these two lines by using a tell block, which specifies the default target for the statements it contains:

tell application "QTShell"
   open the file ""
end tell

Words like "the" are optional, and some words can be abbreviated. (For instance, "application" can be abbreviated as "app".) AppleScript also contains facilities for executing statements conditionally, repeating statements multiple times, assigning values to variables, defining subroutines and error handlers, and so forth.

Apple provides an application called Script Editor that's useful for creating and testing scripts. Figure 1 shows a Script Editor script window.

Figure 1: A Script Editor window

As you can see, the window contains a button to run the script in the window. Typically, however, scripters want to package their work as a standalone double-clickable application, called an applet. We can create an applet using Script Editor by selecting the "Save As..." menu item and then choosing the "Application" format option, as shown in Figure 2.

Figure 2: Creating an applet

Handling Apple Events

Not all applications can respond to scripted instructions. An application that can -- called a scriptable application -- must be able to receive and process Apple events. Apple events are messages sent from one application to another that contain attributes (specifying the event class and kind) and possibly also parameters. (An application can also send Apple events to itself, and that is sometime useful.)

Classes of events that apply to specific kinds of objects are collected together into what are called suites. For example, the Text suite contains Apple events that apply to characters, words, paragraphs, text styles, and so forth. And the QuickTime suite contains Apple events that apply to QuickTime movies and tracks.

Our sample application QTShell is scriptable, but it supports only the four Apple events that must be supported by any scriptable application: Open Application, Open Documents, Print Documents, and Quit. It does not support any other events. In particular, it does not support any of the events belonging to the QuickTime suite. So we can launch QTShell and get it to open a specific movie file by executing the scripts shown above, but it does not know how to start the movie playing (for instance).

In the Carbon world, Apple events are sent to an application as high-level events. In the function QTFrame_HandleEvent, we'll see this case block:

case kHighLevelEvent:

This simply passes the event to the Apple Event Manager, which dispatches it to one of QTShell's installed Apple event handlers.

It's actually quite easy to add the minimal level of scriptability to a Carbon application. When it starts up, QTShell calls the QTApp_InstallAppleEventHandlers function, defined in Listing 1, to install event handlers for the four required Apple events.

Listing 1: Installing Apple event handlers

void QTApp_InstallAppleEventHandlers (void)
   long         myAttrs;
   OSErr      myErr = noErr;
   // see whether the Apple Event Manager is available;
   // if it is, install handlers for the four required Apple Events
   myErr = Gestalt(gestaltAppleEventsAttr, &myAttrs);
   if (myErr == noErr) {
      if (myAttrs & (1L << gestaltAppleEventsPresent)) {
         // create routine descriptors for the Apple event handlers
         gHandleOpenAppAEUPP = NewAEEventHandlerUPP
         gHandleOpenDocAEUPP = NewAEEventHandlerUPP
         gHandlePrintDocAEUPP = NewAEEventHandlerUPP
         gHandleQuitAppAEUPP = NewAEEventHandlerUPP
         // install the handlers
          kAEOpenApplication, gHandleOpenAppAEUPP, 0L, false);
          kAEOpenDocuments, gHandleOpenDocAEUPP, 0L, false);
          kAEPrintDocuments, gHandlePrintDocAEUPP, 0L, false);
          kAEQuitApplication, gHandleQuitAppAEUPP, 0L, false);

The Apple event handlers in QTShell are fairly simple. Indeed, since our application must be launched by the operating system in order to receive the OpenApplication event, we don't need to do anything in response to that event except return noErr. Listing 2 shows the nugatory OpenApplication event handler.

Listing 2: Handling the OpenApplication Apple event

PASCAL_RTN OSErr QTApp_HandleOpenApplicationAppleEvent 
         (const AppleEvent *theMessage, AppleEvent *theReply, 
            long theRefcon)         
#pragma unused(theMessage, theReply, theRefcon)
   // we don't need to do anything special when opening the application

And our PrintDocuments handler (Listing 3) is just as simple, since QTShell does not support printing. In this case, we return a suitable error.

Listing 3: Handling the PrintDocuments Apple event

PASCAL_RTN OSErr QTApp_HandlePrintDocumentAppleEvent 
         (const AppleEvent *theMessage, AppleEvent *theReply, 
            long theRefcon)         
#pragma unused(theMessage, theReply, theRefcon)

QTShell's handler for the QuitApplication Apple event is only slightly less trivial. It just calls the QTFrame_QuitFramework function, as shown in Listing 4.

Listing 4: Handling the QuitApplication Apple event

PASCAL_RTN OSErr QTApp_HandleQuitApplicationAppleEvent 
         (const AppleEvent *theMessage, AppleEvent *theReply, 
            long theRefcon)         
#pragma unused(theMessage, theReply, theRefcon)
   // close down the entire framework and application

The only really interesting Apple event handler in QTShell is the OpenDocuments handler, shown in Listing 5.

Listing 5: Handling the QuitApplication Apple event

PASCAL_RTN OSErr QTApp_HandleOpenDocumentAppleEvent 
         (const AppleEvent *theMessage, AppleEvent *theReply, 
            long theRefcon)         
#pragma unused(theReply, theRefcon)
   long               myIndex;
   long               myItemsInList;
   AEKeyword          myKeyWd;
   AEDescList         myDocList;
   long               myActualSize;
   DescType           myTypeCode;
   FSSpec             myFSSpec;
   OSErr              myIgnoreErr = noErr;
   OSErr              myErr = noErr;
   // get the direct parameter and put it into myDocList
   myDocList.dataHandle = NULL;
   myErr = AEGetParamDesc(theMessage, keyDirectObject, 
                                          typeAEList, &myDocList);
   // count the descriptor records in the list
   if (myErr == noErr)
      myErr = AECountItems(&myDocList, &myItemsInList);
   else {
      myErr = noErr;
      myItemsInList = 0;
   // open each specified file
   for (myIndex = 1; myIndex <= myItemsInList; myIndex++)
      if (myErr == noErr) {
         myErr = AEGetNthPtr(&myDocList, myIndex, typeFSS, 
                           &myKeyWd, &myTypeCode, (Ptr)&myFSSpec, 
                           sizeof(myFSSpec), &myActualSize);
         if (myErr == noErr) {
            FInfo      myFinderInfo;
            // verify that the file type is MovieFileType
            myErr = FSpGetFInfo(&myFSSpec, &myFinderInfo);   
            if (myErr == noErr) {
               if (myFinderInfo.fdType == MovieFileType)
                  // we've got a movie file; just open it
                  QTFrame_OpenMovieInWindow(NULL, &myFSSpec);
   if (myDocList.dataHandle)
      myIgnoreErr = AEDisposeDesc(&myDocList);

Notice that we reset the local variable myErr to noErr if AEGetParamDesc returns an error. That's because, whenever our application receives the OpenApplication event, it also receives an OpenDocuments event, even if no files were explicitly specified to be opened. In that case, AEGetParamDesc would return an error, which would otherwise be returned to the Apple Event Manager.

Scripting QuickTime Player

QTShell is fairly uninteresting from a scripting point of view: we can launch it, get it to open movies files, and later tell it to quit. On the other end of the scriptability spectrum is the application QuickTime Player, which (from version 5.0.2 onward) supports an extensive vocabulary of commands and object specifiers for controlling movies and their elements. For instance, we can tell QuickTime Player to open a specific movie and play it from the beginning with the script shown in Listing 6.

Listing 6: Playing a movie from the beginning

tell application "QuickTime Player"
   open file ""
   tell movie 1
   end tell
end tell

Notice that we specify the movie to be played by providing its index. This works nicely, even if QuickTime Player is already launched and already has one or movie movies open, because the most recently-opened movie will have index 1. We could also specify the movie by name, but the name we specify needs to be the name of the movie window (which, in QuickTime Player, is not always the basename of the movie file).

Or, we can tell QuickTime Player to delete every disabled track by executing the script shown in Listing 7.

Listing 7: Deleting all disabled tracks

tell application "QuickTime Player"
   open file ""
   if not (exists movie 1) then return
   stop every movie
   delete (every track of movie 1 whose enabled is false)
end tell

Note the parentheses in several of these statements. The parentheses indicate that the result of the code inside the parentheses is to be used as an input value to the statement that contains the parenthetical code. For example, the code "exists movie 1" is evaluated and its result, which is a Boolean value, is used as the input of the conditional expression "if not". Similarly, the result of evaluating the expression "every track of..." is a list of disabled tracks; the delete command takes that list as input and (lo and behold) deletes each item in that list.

As I mentioned, the scripting vocabulary supported by QuickTime Player is quite extensive, and we could easily spend an entire article investigating it. But let's move on to our main task, building a QuickTime application using AppleScript Studio.

The Project

AppleScript Studio applications are Cocoa applications in which the Cocoa classes are manipulated using AppleScript scripts. Accordingly, we'll use the same tools, Project Builder and Interface Builder, that we use to develop Cocoa applications driven by Objective-C or Java code.

Creating a New Project

To get started, we'll launch Project Builder and select "New Project..." in the File menu. In the list of available projects, select "AppleScript Application", as in Figure 3.

Figure 3: The New Project window

Let's save the project with the name "ScripTeez" in our home directory (the default location). Figure 4 shows the new project window, with the top-level disclosure triangles opened.

Figure 4: The ScripTeez project window

The "Product" -- that is, our application -- is shown in red because it hasn't been built yet. Let's build and run the application; when we do that, we'll see the window shown in Figure 5.

Figure 5: The default application window

Eventually we'll need to add a movie player view (of type NSMovieView) to this window; but before we do that, let's take a look at a couple of the files in the project. The file main.m is shown in Listing 8. It's just like the main.m file that we encountered in our Objective-C Cocoa application except that it adds a call to the ASKInitialize function, to initialize the AppleScript Kit (a framework that provides the AppleScript support for our application).

Listing 8: Running the application

extern void ASKInitialize();
extern int NSApplicationMain(int argc, const char *argv[]);
int main(int argc, const char *argv[])
   return NSApplicationMain(argc, argv);

For present purposes, we will not need to modify main.m.

The file ScripTeez.applescript is where we'll place our AppleScript code. Out of the box, it's empty except for a few lines of comments.

Modifying the Application Window

Let's put a movie view into the default window. Open the MainMenu.nib file with Interface Builder. (The easiest way to do this is just to double-click the entry in the project window.) Figure 6 shows the main window for this nib file.

Figure 6: The nib file

Select the icon labeled "Window" and then choose the "Show Info" menu item in the Tools menu; in the window that appears, unselect the "Deferred" attribute (as in Figure 7).

Figure 7: The window attributes

Now select the GraphicsViews icon in the toolbar of the palette window. The palette window should then look like Figure 8.

Figure 8: The graphics views panel

Drag a QuickTime icon from the palette into the movie window and resize it so that it looks like Figure 9. There is a 20-pixel border around each edge of the movie view.

Figure 9: The revised application window

Next we need to configure the movie view so that it resizes correctly to maintain that border when the application window is resized. Select the "Size" panel in the Info window and set the springs so that they look like those in Figure 10.

Figure 10: The movie view size attributes

In our Objective-C Cocoa application MooVeez, we needed to make some connections between the movie view and our custom document class, but that isn't necessary here. Instead, we'll refer to the movie view by name in our AppleScript code. So we need to give the movie view a name. Select the "AppleScript" panel in the Info window and set the name of the movie view to "movieView", as in Figure 11.

Figure 11: The movie view name

We are now almost done configuring the application window. The final thing we need to do is attach some event handlers to the application window. These handlers specify some AppleScript code that will be executed when certain specific events occur to that window. In ScripTeez, we care about only two events for the window, namely when it is opened and when it is closed. All other events that pertain to the window will be handled automatically by the underlying Cocoa frameworks.

To attach event handlers to the window, select it and then select the "AppleScript" panel in the Info window. In the top pane of that panel are listed the events to which we can attach AppleScript code. Figure 12 shows how to select the handlers we want to attach, the "awake from nib" handler and the "will close" handler. It also indicates that the AppleScript code for those handlers is to be contained in the file ScripTeez.applescript.

Figure 12: The window event handlers

If we click the "Edit Script" button in the Info window, that file open and we'll see skeletal event handlers already included in it, as in Listing 9. Later on, we'll add some meat to these event handlers.

Listing 9: The skeletal event handlers

-- ScripTeez.applescript
-- ScripTeez
-- Created by Tim Monroe on Thu May 08 2003.
-- Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
on will close theObject
   (*Add your script here.*)
end will close
on awake from nib theObject
   (*Add your script here.*)
end awake from nib


Well, that's all we have time for this month. In the next QuickTime Toolkit article, we'll set up the application's menu and see how to get ScripTeez to open and display QuickTime movies.


Thanks are due to Scott Bongiorno for reviewing this article and providing some useful comments.

Some of the scripts for driving QuickTime Player are modeled on scripts available at

Tim Monroe is a member of the QuickTime engineering team. You can contact him at The views expressed here are not necessarily shared by his employer.


Community Search:
MacTech Search:

Software Updates via MacUpdate

Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
The best games like Animal Crossing on m...
Animal Crossing amiibo Festival is out right now for the Wii U, reminding us of just how much fun that world can be. Or at least to go back and check in on our villages once in a while. [Read more] | Read more »
Between 2 Taps - Tap for Tap interview M...
Hello, and welcome back to Between 2 Taps, Tap for Tap’s Indie Dev interview series. [Read more] | Read more »
Facility 47 (Games)
Facility 47 1.0.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.1 (iTunes) Description: You wake up alone and freezing in an icy cell. You try the cell door but it’s locked, it seems that you are stuck with no... | Read more »
The best Photoshop alternative on iPad
Instagram and Lightroom are great and all, but sometimes people need to get extra creative with their image editing.Like, Photoshop creative. If you're one of these people, take a look at our pick for the best mobile Photoshop experience on iPad... | Read more »
The Walking Dead: No Man’s Land guide -...
A new update for The Walking Dead: No Man’s Land was released last week, making it the perfect time for you to head back to your base and take out some walkers. Here’s the lowdown on what’s new to the game, and how to take advantage. [Read more] | Read more »
Goat Rider guide - Tips and tricks to st...
We've all been there. One second, we're riding high on a crazed goat, and the next, we've been tossed off it like someone who's no good at goat ridin'. [Read more] | Read more »

Price Scanner via

Best Buy Black Friday deals: Up to $200 off M...
Best Buy has posted their Black Friday sale prices for 2015. Save on MacBook Pros, MacBooks, MacBook Airs, iMacs, iPads, and Apple Watches. Choose free shipping or free local store pickup (if... Read more
Save $30-$40 on new Apple TVs after rebate
Adorama has new Apple TVs on sale for up to $40 off MSRP after mail-in rebate, good through December 15th. Shipping is free, and Adorama charges NY & NJ sales tax only: - 32GB Apple TV: $119.99... Read more
13-Inch Haswell MacBook Air At Two Years – Th...
The 13-inch mid-2013 “Haswell” MacBook Air I ordered in Apple’s November 2013 Black Friday sale was my first new Mac in four and a half years — the longest interval I’ve gone between system upgrades... Read more
Target Black Friday Early Access deals: $100...
Target is offering early access to their Black Friday deals on Apple products on their online store for today, the 25th, only. Choose free shipping or free local store pickup (if available): - Apple... Read more
BlackBerry Q3 Mobility Index Report Finds iOS...
BlackBerry has announced results of its thirteenth Good Mobility Index Report, showing that organizations are increasingly building custom secure apps. Among Good Powered by BlackBerry (formerly Good... Read more
Wednesday roundup of early Black Friday Mac s...
Save up to $500 on a new Mac with these early Black Friday deals from Apple resellers, currently the lowest prices available for these models: (1) B&H Photo has all new Macs on sale for up to $... Read more
iPod nano on sale for $119, $30 off MSRP
Walmart has the 16GB iPod nano (various colors) on sale for $119.20 on their online store for a limited time. That’s $30 off MSRP. Choose free shipping or free local store pickup (if available). Sale... Read more
Adorama Black Friday deals: Up to $400 off Ma...
Adorama has released their Black Friday deals for 2015. Save up to $400 on MacBook Pros, $200 on MacBooks and MacBook Airs, and $270 on iMacs. Use code RYBFDEAL during checkout to see these prices.... Read more
B&H Photo Deals: $200 off 12-inch 1.2GHz...
In addition to the B&H Photo Black Friday week sales we posted yesterday, B&H has lowered their price on two products to $200 off MSRP: - 12″ 1.2GHz Gray Retina MacBook: $1399 save $200 - 13... Read more
Best Buy Early Access: Today only, Up to $125...
Best Buy has iPad Air 2s on sale for up to $125 off MSRP and Apple Watch models on sale on their online store for up to $100 off MSRP with special codes through midnight CT tonight. Choose free... Read more

Jobs Board

Hardware Systems Integration Engineer - *App...
# Hardware Systems Integration Engineer - Apple Watch Job Number: 39380139 Santa Clara Valley, Califo ia, United States Posted: Apr. 23, 2015 Weekly Hours: **Job Read more
Sr. Technical/Project Manager, *Apple* Educ...
# Sr. Technical/Project Manager, Apple Education Job Number: 36588557 New York City, New York, United States Posted: Jul. 30, 2015 Weekly Hours: 40.00 **Job Summary** Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Merchant Operations Manager: *Apple* Pay -...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
*Apple* Pay QA Manager - Apple Inc. (United...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.