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

Pocket Arcade Story (Games)
Pocket Arcade Story 1.00 Device: iOS Universal Category: Games Price: $4.99, Version: 1.00 (iTunes) Description: Here comes a new challenger: it's the arcade simulation game you've been waiting for! Build your very own gaming... | Read more »
How to get coins faster in Rodeo Stamped...
There comes a time in a cowboy or cowgirl's life when all the riding and lassoing skills in the world aren't enough. You're going to need some cold, hard cash to keep your sky zoo expanding in Rodeo Stampede. [Read more] | Read more »
How to out-do Cam Newton in Can You Dab?
The thing about dance crazes is that you're never really sure when they've run their course. Take the Dab, for instance. Propelled by its adoption as the touchdown celebration of choice for Carolina Panthers quarterback Cam Newton, the Dab seemed... | Read more »
Artik Games releases Splashy Cats for An...
Splashy Cats had us hooked from the title alone, and when we found out the game was literally just zig-zagging one of our favourite pop-culture references, guised as a playable cat character, down a river – our appetites were whetted to say the... | Read more »
Battle Cars (Games)
Battle Cars 1.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1 (iTunes) Description: Welcome to the world of Battle Cars. Battle Cars is a classic arcade top-down racing game with fast mini cars and funny weapons to... | Read more »
How to get started with
One could be forgiven for thinking that there are already plenty of streaming video apps out there. It's just that the App Store charts would insist that you're mistaken. [Read more] | Read more »
Rodeo Stampede: Guide to all Savannah an...
A "gotta catch 'em all" joke seems appropriate here, even though we're talking animals in Rodeo Stampede and not pocket monsters. By now you've probably had plenty of rides, tamed some animals and built yourself a pretty nice zoo | Read more »
Is there cross-platform play in slither....
So you've sunken plenty of hours into crawling around in on your iPhone or iPad. You've got your stories of tragedy and triumph, the times you coiled four snakes at one time balanced out by the others when you had a length of more than... | Read more »
Rodeo Stampede guide to running a better...
In Rodeo Stampede, honing your skills so you can jump from animal to animal and outrun the herd as long as possible is only half the fun. Once you've tamed a few animals, you can bring them home with you. [Read more] | Read more »
VoxSyn (Music)
VoxSyn 1.0 Device: iOS Universal Category: Music Price: $6.99, Version: 1.0 (iTunes) Description: VoxSyn turns your voice into the most flexible vocal sound generator ever. Instantly following even subtle modulations of pitch and... | Read more »

Price Scanner via

Why Use Indie Opera And Vivaldi Instead Of Sa...
For many years my web browser workhorses were various permutations and spinoffs of the Netscape/Mozilla/Firefox Open Source platform, and the Norwegian indie browser Opera, which I took a shine to... Read more
Western Digital Launches Worlds Fastest 256GB...
At the Mobile World Congress in Shanghai Western Digital Corporation this week introduced a new suite of 256 gigabyte (GB) microSD cards, which includes the new 256GB SanDisk Extreme microSDXC UHS-I... Read more
KeyCue 8.1 Integrates With Typinator To Displ...
Ergonis Software has released KeyCue 8.1, a new version of the company’s keyboard shortcut cheat sheet. KeyCue 8 introduced a new way to define a wide variety of triggers, which can be used to... Read more
Save up to $600 with Apple refurbished Mac Pr...
Apple has Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The following... Read more
21-inch 2.8GHz iMac on sale for $1199, save $...
Amazon has the 21″ 2.8GHz iMac (model #MK442LL/A) on sale for $1199.99 including free shipping. Their price is $100 off MSRP, and it’s the lowest price available for this model. Read more
13-inch 2.5GHz MacBook Pro (Apple refurbished...
Apple has Certified Refurbished 13″ 2.5GHz MacBook Pros available for $829, or $270 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros... Read more
MacBook Airs on sale for up to $50-$100 off M...
B&H Photo has 13″ and 11″ MacBook Airs on sale for up to $100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 11″ 1.6GHz/128GB MacBook Air: $849 $50 off list price - 11″ 1.... Read more
Brexit Vote Result Forecast To Slash UK 2016...
Uncertainty and economic volatility can be expected to increase over the next nine months, as the Brexit and concerns over the future of the EU hit IT investment, say Canalys market analysts, with... Read more
13-inch 256GB MacBook Air on sale for $1149,...
Amazon has the 2016 13″ 1.6GHz/256GB MacBook Air (model MMGG2LL/A) on sale for $1149.99 including free shipping. Their price is also $50 off MSRP. Read more
Haven App Launches New Age Of Wirless 911 Eme...
Haven from RapidSOS represents a transformation in access to emergency services from a phone call solely dependent on voice to a robust data connection for voice, text, medical/demographic data.... Read more

Jobs Board

*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* Retail - Multiple Positions, Willow...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.