Read Digital Edition


ADS BY GOOGLE
Top Three Links You Must Click On


Creating a Video Player Using Adobe ActionScript 3.0
When you create a Flash Media Server 2 application, you typically place emphasis on optimizing the quality of the communications

When you create a Flash Media Server 2 application, you typically place emphasis on optimizing the quality of the communications. That is certainly as it should be. Likewise, quality object-oriented programming (OOP) is another priority. One standard in OOP is design patterns-abstract concepts for solving recurring problems using designs that optimize OOP when you apply them appropriately. The seminal work in design patterns is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm Ralph Johnson, and John Vlissides, affectionately known as "The Gang of Four" or simply GoF.

One design pattern in particular, the state design pattern (or SDP), focuses on the different states in an application, transitions between states, and the different behaviors within a state. A simple Flash video player application, for example, has two states: Stop and Play. In the Stop state, the video is not playing; in the Play state, a video is playing. Furthermore, the player transitions from the Stop state to the Play state using a method that changes the application's state. Likewise, it transitions from Play to Stop using a different transition and method to make it happen.

An interface holds the transitions, and each state implements the transitions as methods that are unique to that state. Each method is implemented differently depending on the context of its use. For example, the startPlay() method would do one thing in the Stop state and something entirely different the Play state, even though startPlay() is part of both states. To understand and appreciate the value of the SDP, it helps to understand something about state machines.

This article begins with a simple two-state application that plays and stops playing an FLV file. It requires only Flash Player 9 and ActionScript 3.0, which you can download from the links below. The initial application introduces the basics of a state machine and the state design pattern.

The application is then expanded into a more robust one using the same state structure and incorporating Flash Media Server 2. This illustrates both the expandibility of an application using a design pattern and the process of incorporating Flash Media Server 2 into that design using ActionScript 3.0.

State machines and statecharts A state machine is the conceptual model of states you would be using in an application with the SDP; the actual application is the state engine. So if my video player application is designed around key states, that design represents the state machine. However, one need not worry about which is which because they're used differently and interchangeably in the literature on state machines. The important point to keep in mind is the idea of states and their differing contextual behavior.

Rather than beginning with the usual diagrams associated with design patterns, I'll start with a statechart. At its most basic level, a statechart is an illustration of an application's states and transitions. As such, it is a model for the state machine and engine. Taking a simple video player application, you can see the Play and Stop states. When the application is first run, the application enters the Stop state and can transition only to the Play state (see Figure 1).

The line going from the black dot to the Stop state shows the Application Not Running state. For all intents and purposes, however, assume that the starting point is the Stop state. This could be illustrated in a hierarchical state with Application Running and Application Not Running states, or you could even place the whole hierarchy into Computer On and Computer Off states, but that's not too useful because you aren't coding to those states.

Before I discuss getting from one state to another, consider what each state can actually do. In the Stop state, I can initiate only the Play state. That is, I cannot stop in the Stop state because I'm already stopped. By the same token, if I'm in the Play state, the only thing I can do is transition to the Stop state.

Transitions The transitions in a state machine are the actions that change states. In the simple statechart, the line from Stop to Play would be a startPlay() method of some sort; and from Play to Stop, it would be a stopPlay() method. As more states are added, you might find that you cannot transition directly from one state to another. Rather, you have to go through a series of states to get where you want to go. As you will see further on, if you're in the Stop state, you cannot go directly to the Pause state. You have to go first to the Play state before going to the Pause state.

Triggers Finally, to initiate a transition, you need some kind of trigger. A trigger is any event that initiates a transition from one state to another. Usually we think of some kind of user action as a trigger, such as a mouse movement or button click. However, in simulations certain states can be triggered by ongoing conditions, such as running out of simulated fuel, draining a simulated battery, or a collision with an object. Likewise, triggers are subject to contexts and should work only in the appropriate contexts to initiate a state. So while you might use a Play button to initiate the Play state from the Stop state, it should not trigger a Play state from the Play state.

Often triggers are placed along with the transitions on the statecharts. This helps identify the trigger events and the transitions they trigger. Figure 2 shows the statechart updated to include both the triggers and transitions they initiate.

If you're interested in more information about using state engines, statecharts, and the more general aspects of working with Flash and states, see Flash MX for Interactive Simulation by Jonathan Kaye and David Castillo (Thomson, 2003). Although it goes back a couple generations of Flash, the book is timeless in its concepts and shows some very smooth device simulations.

State design pattern Fortunately, one of the original design patterns that GoF described is the State pattern. Closely resembling the Strategy pattern, the State pattern is used when an application's behavior depends on changing states at runtime or has complex conditional statements that branch depending on a current state (see Figure 3). When the internal states change, an object alters its behavior when designed using the State pattern.

Using the SDP, all of the behaviors (methods) for a single state are placed into single objects (concrete states), and all transition behaviors for the application (state machine) are placed into a single interface. Each state object implements the interface in a fashion appropriate for the state. Because of this structure, no conditional statements are required to branch differentially depending on the current state. Rather than writing complex conditional statements, the individual state objects define how the methods are to behave for that state.

For example, with a two-state machine (Play and Stop) the following pseudo code could direct the state behavior to start playing the video depending on the state machine's current state:

function doPlay():void{
     if(state == Play)
     {
        trace("You're already playing.");
     }
     else if (state == Stop)
     {
        trace("Go to the Play state.");
     }
}

Note: By the way, an important but small difference between ActionScript 2.0 and ActionScript 3.0 is that all void special types are in lowercase. In ActionScript 2.0 the first letter was in caps: Void. Watch out for that!

With a couple of states, that's not too difficult. As you add states, however, things get more complicated and you're swimming in a sea of conditional statements that all have to work in sync.

The alternative is to set up "contextual" behavior using a State pattern. For example, the following code has two different objects with different implementations of behaviors from an interface:

//Interface
interface State
{
    function startPlay():void;
    function stopPlay():void;
}
//Play State object
class PlayState implements State
{
    public function startPlay():void
    {
        trace("You're already playing");
    }
    public function stopPlay():void
    {
        trace("Go to the Stop state.");
    }
}
//Stop State object
class StopState implements State
{
    public function startPlay():void
    {
        trace("Go to the Play state.");
    }
    public function stopPlay():void
    {
        trace("You're already stopped");
    }
}

As you can see, the behaviors (methods) have different implementations in the different states. When you add more states, all you need to do is add their transitional behaviors to the interface and create a new concrete state (class) that implements them. Each new behavior needs to be added to the existing state classes.

Context manager in a state design pattern To manage the states and their transitions, you need some kind of management object-something to keep track of everything in the state machine. In Figure 3 the Context box is the abstraction of the state engine. The context manages the different states that make up the state machine and contain the different states. Figure 4 shows a more concrete representation of what needs to be transformed.

Creating a context class In looking at the example of creating a simple video player, we need a context that will serve to get and set the different states. So the next phase will be to look at a class (object) that does just that. Let's first take a look at the class, and then you'll see what's going on:

01 class VideoWorks
02 {
03     var playState:State;
04     var stopState:State;
05     var state:State;
06     public function VideoWorks()
07     {
08         trace("Video Player is On");
09         playState = new PlayState(this);
10         stopState = new StopState(this);
11         state = stopState;
12     }
13     public function startPlay():void
14     {
15         state.startPlay();
16     }
17     public function stopPlay():void
18     {
19         state.stopPlay();
20     }
21     public function setState(state:State):void
22     {
23         trace("A new state is set");
24         this.state = state;
25     }
26     public function getState():State
27     {
28         return state;
29     }
30     public function getPlayState():State
31     {
32         return this.playState;
33     }
34     public function getStopState() :State
35     {
36         return this.stopState;
37     }
38    }


About William B. Sanders
William B. Sanders is currently a professor of Sociology and Interactive Information Technology at the University of Hartford in West Hartford, Connecticut, of which he was a founding faculty member. He has published over 40 computer books, including eight on Flash, ActionScript, or Flash Communication Server. Bill founded Sandlight Productions in 1984 as a computer book and software publication company, which has evolved over the past 22 years into an Internet development company specializing in Flash, ActionScript, and Flash Communication Server applications, along with e-business strategies. He has worked with computers ever since his alma mater, the University of California at Santa Barbara, was one of only four nodes on ARPANET, along with UCLA, Stanford University, and the University of Utah. When he's not writing, he updates his websites at sandlight.com and iit.hartford.edu. Bill recently published an instructional video on using Flash Media Server 2 for authorized training provider Train Simple.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

When you create a Flash Media Server 2 application, you typically place emphasis on optimizing the quality of the communications. That is certainly as it should be. Likewise, quality object-oriented programming (OOP) is another priority. One standard in OOP is design patterns-abstract concepts for solving recurring problems using designs that optimize OOP when you apply them appropriately. The seminal work in design patterns is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm Ralph Johnson, and John Vlissides, affectionately known as 'The Gang of Four' or simply GoF.

When you create a Flash Media Server 2 application, you typically place emphasis on optimizing the quality of the communications. That is certainly as it should be. Likewise, quality object-oriented programming (OOP) is another priority. One standard in OOP is design patterns-abstract concepts for solving recurring problems using designs that optimize OOP when you apply them appropriately. The seminal work in design patterns is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm Ralph Johnson, and John Vlissides, affectionately known as 'The Gang of Four' or simply GoF.


  Subscribe to our RSS feeds now and receive the next article instantly!
In It? Reprint It! Contact advertising(at)sys-con.com to order your reprints!
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE
This past weekend I set out explore some of the extension capabilities of Google Wave. One of the we...
More good news for cloud computing! Google last week released its once mysterious Chrome Operating S...
There's a lot of talk about how we need to focus on our buyers' issues and provide them educational ...
SugarCRM, the world’s leading provider of open source customer relationship management (CRM) softwa...
In CloudBerry Lab we are striving to make our customer service better. In this competitive market wi...
We talk a lot about social media on Marketing Trenches. And for good reason – Social media seems to...
Intel has put out its promised beta SDK for Windows (C and C++) and Moblin (C) developers working on...
InformationWeek stumbled on a Microsoft patent application dating back to 2006 deceptively titled “M...
Berlin-based ThinPrint AG, the printer virtualization house, thinks it’s got a cloud solution for th...
IBM has acquired Guardium, a seven-year-old subsidiary of Israel’s Log-On Software transplanted to M...
But on the web, access to services is implicit in the fact that the business is offering the service...
Behaving like it’s got a future, Sun Monday put out what it calls a significant new version of Virtu...
Oracle has offered to cordon off MySQL inside a combined Oracle-Sun to get the European Commission t...
The second set of charges filed last week against Indian outsourcer Satyam Computer Services founder...
Gartner told Reuters that it overestimated how many PCs Acer shipped in the last seven quarters by a...
Office Web Apps, Microsoft’s answer to Google Apps, are supposed to be out sometime in June along wi...
Gartner thinks the server business has stopped sliding into the abyss. Third-quarter sales weren’t a...
Gartner is buying ~$40 million-a-year AMR Research Inc for close to $64 million in cash. AMD special...
Singed by user reaction to its plans to up the price of its support contracts, SAP Tuesday postponed...
Apparently Google Gears ain’t gonna stick around that long. Google Apps will eventually get their of...