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

Latest Forum Discussions

See All

Soft Drummer (Music)
Soft Drummer 1.0 Device: iOS Universal Category: Music Price: $14.99, Version: 1.0 (iTunes) Description: Soft Drummer is the closest thing to a pro session subtle drummer in your pocket. Easy to use and fast, it's much more than a... | Read more »
Is GO Gear the Pokemon GO map app you...
Now that we've settled into something of a Pokemon GO status quo, the number one desire of most players can best be summed out by modifying a quote from Rod Tidwell of Jerry Maguire: "Show me the Pokemon!" [Read more] | Read more »
Rodeo Stampede update: Mountains, new an...
The Savannah and Jungle were just the beginning in Rodeo Stampede. Get ready to head for the Mountains. I think I heard that in a beer ad once. [Read more] | Read more »
COSMOS RINGS 1.0.0 Device: iOS iPhone Category: Games Price: $5.99, Version: 1.0.0 (iTunes) Description: This game cannot be played without the Apple Watch.Released anniversary sale until August 31,2016 PST! A tragic tale of time's... | Read more »
How to get started selling on Mercari
As far as ecommerce has come over the last decade or so, there's still a tremendous opportunity to make it easier for people to buy and sell goods. That's especially true when it comes to shopping apps, which should only continue to increase in... | Read more »
Human Anatomy Atlas 2017 Edition - Compl...
Human Anatomy Atlas 2017 Edition - Complete 3D Human Body 1.0.24 Device: iOS iPhone Category: Medical Price: $24.99, Version: 1.0.24 (iTunes) Description: | Read more »
Heroes of Normandie (Games)
Heroes of Normandie 1.5 Device: iOS Universal Category: Games Price: $14.99, Version: 1.5 (iTunes) Description: The game does not support iPhone 4s and below | Read more »
Why you should never power up Pokemon in...
There's no question that candy is dandy in Pokemon GO. You need big quantities of it to evolve your Pokemon, and when combined with stardust, it can be used to power up your favorite pocket monsters as well, making them more formidable for the gym... | Read more »
Webzen launches 3D MMORPG MU Origin on i...
Mu Origin is featured time and time again at the very top of App Stores in China, and within the top five worldwide top-grossing charts on Google Play.Its popularity in Korea and China, featuring more than 120 registered players in China and 6... | Read more »
Severed (Games)
Severed 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: LAUNCH DISCOUNT ON NOW!! ENDS AUGUST 4! ==== Take control of a one-armed warrior named Sasha, wielding a living sword on her journey... | Read more »

Price Scanner via

Second-Quarter Tablet Shipments Fell 4.8% –...
The latest report from the global market research firm TrendForce finds that worldwide tablet shipments for this second quarter totaled 33.54 million units, representing a quarterly drop of 4.8% and... Read more
Global Smartphone Sales Volumes Mark Second S...
According to preliminary results from the International Data Corporation (IDC) Worldwide Quarterly Mobile Phone Tracker, vendors shipped a total of 343.3 million smartphones worldwide in the second... Read more
Apple TVs on sale for $20-$40 off MSRP
Best Buy has 32GB and 64GB Apple TVs on sale for $20-$40 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store... Read more
Mac minis on sale for $50-$100 off MSRP
B&H Photo has Mac minis on sale for $50 off MSRP including free shipping plus NY sales tax only: - 1.4GHz Mac mini: $449 $50 off MSRP - 2.6GHz Mac mini: $649 $50 off MSRP - 2.8GHz Mac mini: $949... Read more
Clearance 2015 13-inch MacBook Airs available...
B&H Photo has clearance 2015 13″ MacBook Airs available for $300 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $799... Read more
Apple certified refurbished iPad mini 4s avai...
Apple has certified refurbished iPad mini 4s now available for up to $120 off the cost of new models. An Apple one-year warranty is included with each iPad, and shipping is free. The following models... Read more
Notebook Makers In No Rush To Adopt USB-C – R...
Digitimes’ Cage Chao and Joseph Tsai note that while the USB Type-C interface is enjoying growing popularity among smartphones and tablet makers, notebook and all-in-one (AIO) PC vendors (other than... Read more
iMacs on sale for up to $250 off MSRP
B&H Photo has 21″ and 27″ Apple iMacs on sale for up to $250 off MSRP including free shipping plus NY sales tax only: - 27″ 3.3GHz iMac 5K: $2049 $250 off MSRP - 27″ 3.2GHz/1TB Fusion iMac 5K: $... Read more
12-inch 1.1GHz Retina MacBooks on sale for up...
Amazon has 2016 12″ 1.1GHz/256GB Retina MacBooks on sale for up to $100 off MSRP including free shipping: - 12″ 1.1GHz Space Gray Retina MacBook: $1199 $100 off MSRP - 12″ 1.1GHz Silver Retina... Read more
Bare Bones Software Releases Free TextWrangle...
Bare Bones Software has announced the release and immediate availability of TextWrangler 5.5, a significant update to its powerful, free, general purpose text editor for Mac OS X. TextWrangler is a... Read more

Jobs Board

*Apple* Solutions Consultant - APPLE (United...
Job Summary As an Apple Solutions Consultant, you'll be the link between our future customers and our products. You'll showcase your entrepreneurial spirit as you Read more
Lead *Apple* Solutions Consultant - APPLE (...
Job Summary The Lead ASC is an Apple employee who serves as the Apple business manager and influencer across a number of Reseller locations. The Lead ASC's role Read more
*Apple* Retail - Multiple Positions, Charles...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions, Willow...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Evangelist - JAMF Software (United S...
The Apple Evangelist is responsible for building and cultivating strategic relationships with Apple 's small and mid-market business development field teams. This Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.