Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

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    }


More Stories By 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.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
n d 08/20/06 10:47:25 AM EDT

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.

n d 08/19/06 03:49:18 PM EDT

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.

IoT & Smart Cities Stories
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Published in Silicon Valley, Silicon India magazine is the premiere platform for CIOs to discuss their innovative enterprise solutions and allows IT vendors to learn about new solutions that can help grow their business.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.