How to Build a Simple FLV Player in Flash and Flex using the PureMVC Framework.

WARNING * THE FLV CONTAINED WITHIN THIS DEMO TUTORIAL CONTAINS MILDLY OFFENSIVE LANGUAGE FROM A RECORD BEING PLAYED WHILST BEING SCRATCHED IN A RHYTHMIC MANNER ☺

** NOTE ** This app uses the pre V2 PMVC package ** update coming soon!

Requirements:

Software: Flex Builder 3 + Flash CS3
Plugins: PureMVC.swc

Overview:

This is a really basic application constructed using Flex Builder for all ActionScript code and Flash CS3 for the visual components. The purpose of the tutorial is to show how to construct a simple Flash CS3 application using the PureMVC framework. The tutorial should give you working knowledge of how to interact with components on the stage in Flash from within the PureMVC framework. We will use the FLVPlayback component as an example and create an event listener in a mediator to listen out for a click on the FLVPlayback component. This tutorial will not be going into great depth about the framework but simply give you a step by step guide of how to get the framework up and running in a real life application.

1) Start Flex Builder 3 and create a new ActionScript project named CS3VideoPMVC, keep the default settings on the first new project page and click next. We need to have access to the FLVPlayback component classes so click to add another swc and navigate to the FLVPlaybackAS3.swc located within Configuration > Components > Video in the default Flash CS3 installation directory. Click browse on the main source folder option, select the CS3VideoPMVC folder and click new, this will create a standard src folder for all the source files we will create. Click finish. Right click the project folder and select ActionScript compiler, deselect HTML wrapper, we can leave the generation of the HTML page to Flash. Finally create a new folder in the src folder named assets and place an flv for the application to play.

2) Start Flash CS3 and follow the instructions provided by Cliff for importing the framework into Flash (or you can copy the whole PureMVC org directory into the src folder in Flex). Next create a new flash file (ActionScript 3), save it as CS3VideoPMVC in the src folder in the CS3VideoPMVC directory created in Flex. Set the document properties to: width = 320, height = 240, frame rate = 31. Create a new movie clip and name it VideoMC, ensure the linkage properties are displayed by clicking advanced and check export for ActionScript, assigning CS3VideoPMVC as the class, click OK. Drag and instance of this movie clip onto the stage and give it an instance name of player. Double click on the clip and drag an FLVPlayback component onto the stage and give it an instance name of flv_player. In the component inspector set the skin to SkinOverPlaySeekMute.swf. In publish settings select the Flash tab and click ActionScript version settings, deselect automatically declare stage instances and click ok. We are now finished editing in the Flash IDE, however, keep Flash open for publishing and publish preview of the application.

3) In Flex create a new AS3 class named CS3VideoPMVC. This is the class, which will tie the components on the stage in the fla to the PureMVC framework. Create 2 public variables, one named player data typed to MovieClip and the second named flv_player data typed to FLVPlayback. These are the instances of the components on the stage in flash, we now want to get a reference to the PureMVC framework inside this class.

4) Within in the src folder create a new folder called com, then within that folder create a new folder named nutrixinteractive. Create 3 new folders within the puremvc folder named model, view and controller.

5) In the nutrixinteractive folder create a new ActionScript class named ApplicationFacade, click browse next to superclass and type Façade, this will import the PureMVC Façade class. Click add next to interfaces and type IFacade to implement the IFacade class. Deselect generate constructor from super class and generate functions inherited from interfaces then click finish.

6) Type the following to complete your ApplicationFacade class:

Actionscript:
  1. package com.nutrixinteractive
  2. {
  3.     import com.nutrixinteractive.controller.StartupCommand;
  4.    
  5.     import org.puremvc.interfaces.IFacade;
  6.     import org.puremvc.patterns.facade.Facade;
  7.     import org.puremvc.patterns.observer.Notification;
  8.     
  9.     public class ApplicationFacade extends Facade implements IFacade
  10.     {
  11.         // Notification name constants
  12.         public static const STARTUP:String           = "startup";
  13.        
  14.         /**
  15.                  * Singleton ApplicationFacade factory method
  16.          */
  17.         public static function getInstance():ApplicationFacade
  18.         {
  19.             if ( instance == null ) instance = new ApplicationFacade();
  20.             return instance as ApplicationFacade;
  21.         }
  22.         
  23.         public function startup( app:CS3VideoPMVC ):void
  24.         {
  25.             notifyObservers( new Notification( STARTUP, app ) );
  26.         }
  27.         
  28.         /**
  29.          * Register Commands with the Controller
  30.          */
  31.         override protected function initializeController():void
  32.         {
  33.             super.initializeController();
  34.             
  35.             registerCommand( STARTUP, StartupCommand );
  36.         }
  37.     }
  38. }

What is happening here is a check to see if there is already and instance of the ApplicationFacade, if not create one, this is called a creating a Singleton Class. Next is our startup method that expects to me passed the instance of our main application. A notification named STARTUP is then sent to anyone listening (or Observing) and the main application instance is passed as a parameter. The ApplicationFacade is listening and has STARTUP as a named constant and has also registered it to a command. The command to be run is StartupCommand.

7) Within the controller folder create a new ActionScript class named StartupCommand with a super class of SimpleCommand and the interface ICommand. Deselect generate constructor from super class and generate functions inherited from interfaces then click finish.

8) Ensure your StartupCommand looks like below:

Actionscript:
  1. package com.nutrixinteractive.controller
  2. {
  3.     import com.nutrixinteractive.view.PlayerMediator;
  4.     
  5.     import org.puremvc.interfaces.ICommand;
  6.     import org.puremvc.interfaces.INotification;
  7.     import org.puremvc.patterns.command.SimpleCommand;
  8.     
  9.     public class StartupCommand extends SimpleCommand implements ICommand
  10.     {
  11.         /**
  12.          * Register the Proxies and Mediators
  13.          *
  14.          * Get the View components for the Mediators from the app,
  15.          * which passed a reference to itself on the notification.
  16.          */
  17.          override public function execute( note:INotification ):void
  18.          {
  19.              var app:CS3VideoPMVC = note.getBody() as CS3VideoPMVC;
  20.               
  21.              // Register Mediators
  22.              facade.registerMediator( new PlayerMediator( app ) );
  23.          }
  24.     }
  25. }

The ApplicationFacade (our hub) calls this command. When notifyObservers() was run from the startup method it passed an instance of the main application that we can retrieve using getBody() method on this notification. It is from this command we can now initiate (register) a mediator to handle interaction with the main application.

9) Within the view folder create a new ActionScript class named PlayerMediator with a super class of Mediator and the interface I Mediator. Deselect generate constructor from super class and generate functions inherited from interfaces then click finish.

10) Ensure your PlayerMediator looks as below:

Actionscript:
  1. package com.nutrixinteractive.view
  2. {
  3.     import fl.video.*;
  4.    
  5.     import flash.display.Sprite;
  6.     import flash.events.MouseEvent;
  7.    
  8.     import org.puremvc.interfaces.IMediator;
  9.     import org.puremvc.patterns.mediator.Mediator;
  10.  
  11.     public class PlayerMediator extends Mediator implements IMediator
  12.     {
  13.         // Mediator name
  14.         public static const NAME:String = 'PlayerMediator';
  15.        
  16.         // Visuals on stage
  17.         private var flv_player:FLVPlayback;
  18.        
  19.         /**
  20.          * Constructor
  21.          */
  22.         public function PlayerMediator( viewComponent:Object )
  23.         {
  24.             // Pass the viewComponent to the superclass
  25.             super( viewComponent );
  26.            
  27.             assignPlayer();
  28.         }
  29.        
  30.         override public function getMediatorName():String
  31.         {
  32.             return PlayerMediator.NAME;
  33.         }
  34.         
  35.         protected function get player():CS3VideoPMVC
  36.         {
  37.             return viewComponent as CS3VideoPMVC;
  38.         }
  39.         
  40.         private function assignPlayer():void
  41.         {   
  42.              flv_player = player.flv_player;
  43.             
  44.              flv_player.addEventListener( MouseEvent.CLICK, onClick );
  45.             
  46.              playVideo();
  47.         }
  48.        
  49.         private function playVideo():void
  50.         {
  51.             flv_player.play("assets/krome.flv");
  52.         }
  53.        
  54.         private function onClick( e:MouseEvent ):void
  55.         {
  56.             trace(" CLICK ");
  57.         }
  58.     }
  59. }

The mediator is passed an instance of the main application and using a getter method enables the main application to be referenced as ‘player’. We create a local variable to the FLVPlayback component and now have direct access to add an event listener.

11) Finally to tie the application together ensure your CS3VideoPMVC.as class looks as below:

Actionscript:
  1. package
  2. {
  3.     import com.nutrixinteractive.ApplicationFacade;
  4.    
  5.     import fl.video.FLVPlayback;
  6.     import flash.display.MovieClip;
  7.  
  8.     public class CS3VideoPMVC extends MovieClip
  9.     {
  10.         public var player:MovieClip;
  11.         public var flv_player:FLVPlayback;
  12.        
  13.         public function CS3VideoPMVC()
  14.         {
  15.             ApplicationFacade.getInstance().startup(this);
  16.         }
  17.     }
  18. }

Here we create the 2 local variables, which are the component instances on the stage. We then instantiate the ApplicationFacade directly calling the startup method passing a single parameter, the instance of the documentClass which is home to our player MovieClip and flv_player FLVPlayback component.

12) Run the application in Flash. And click the controls on the component. A trace should display in the Flash output window.

Where next?

Now you can access components on the stage from within the PureMVC framework why not add your own controls. You can also set up a Proxy to get an external play list and pass that to the mediator for the FLVPlayback component to play. Now the basic structure is in place adding to the framework is a synch.

Source Files: source

*** NOTE UPDATE 1 ***

  • Package restructured.
  • Mac OS X structures deleted
  • Swf, javascript and html files removed

*** NOTE UPDATE 2 ***

  • Added the puremvc org directory to the src folder in source files.
  • Amended tutorial accordingly.

*** copyright newtriks 2008 ***

This entry was posted in AS3, Flash, Flex, PureMVC, Tutorials and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

30 Comments

  1. andrey
    Posted January 15, 2008 at 4:23 pm | Permalink

    Thanks for the tutorial, but after runnig the application in Flash I got 3 errors:
    1017: The definition of base class Facade was not found.
    1045: Interface IFacade was not found.
    1020: Method marked override must override another method.

    Thanks.

  2. Posted January 15, 2008 at 5:12 pm | Permalink

    Hi andrey, have you imported imported the puremvc framework into your project? I have found some one had a similar problem and I may not have had the issue due to me importing it following these instructions puremvc flash install, an easy way to get puremvc is to copy the org directory from puremvc and paste it into the src folder in Flex, I will amend the tutorial accordingly :)

  3. andrey
    Posted January 16, 2008 at 10:37 am | Permalink

    Thank you! It works!

  4. Tronfucius
    Posted January 16, 2008 at 1:22 pm | Permalink

    Thanx for a nice intro into PMVC. I like the twich of doing a Flash-app with code repository in Flex. I usually do it the other way around. I see a lot of similarities between PMVC and Cairngorm, however being a Cairngormer PMVC still is new to me, but this looks really promising.
    Thanx again NewTriks!

  5. Russ
    Posted January 17, 2008 at 6:06 pm | Permalink

    I am getting this error that I have gotten before on other examples
    "Cannot access a property or method of a null object reference at com.infusion.view::PlayerMediator/assignPlayer()"
    It seems that the viewComponent isn't getting registered before it is being accessed. Like the PlayerMediator is not really sending the viewComponent to it's parent?
    played around with it for a while, but I couldn't get it to work.
    It seems I only get this error when creating a Flash movie, not Flex.
    I guess I will check out the PureMVC forums
    Russ

  6. Russ
    Posted January 17, 2008 at 8:22 pm | Permalink

    yeah it's always the little things that shut you down, like spelling....
    veiwComponent != viewComponent
    I went back and checked the other example I a was following, and I had mad the same mistake...

  7. Posted February 10, 2008 at 10:09 pm | Permalink

    Alexie has translated my tutorial into Russian for all adept to the lingo :) Thanks Alexie http://injun.ru/?p=450

  8. tamt
    Posted April 9, 2008 at 10:39 am | Permalink

    nice

  9. Posted April 22, 2008 at 9:09 pm | Permalink

    hey

    Really nice tips!

    need to try to do it myself, implemeting your ideas

    thanks!

  10. Posted April 30, 2008 at 10:08 am | Permalink

    Hi,

    looking good, nice article

    thanks for sharing this!

  11. Posted April 30, 2008 at 5:46 pm | Permalink

    Responding to Russ above. i had the same problem. A colleague looked it over and pointed out that a change in PureMVC_AS3_2_0_1 requires an update to PlayerMediator() in PlayerMediator.as:

    public function PlayerMediator( viewComponent:CS3VideoPMVC )
    {
    //pass the viewComponent to the superclass
    super (NAME, viewComponent ); //modified this
    assignPlayer();
    }

    Summary: super() now requires two parameters--the first parameter is the name.

  12. Posted April 30, 2008 at 9:15 pm | Permalink

    Here is the link to the migration from 1.7.1 to 2.0 for reference http://trac.puremvc.org/PureMVC_AS3/wiki/ReleaseNotes

    Simon

  13. Posted May 17, 2008 at 4:33 pm | Permalink

    Thanks!

  14. Posted May 25, 2008 at 11:39 am | Permalink

    Thanks!

  15. Joel
    Posted June 5, 2008 at 11:25 am | Permalink

    override public function execute( note:INotification ):void
    {
    var app:CS3VideoPMVC = note.getBody() as CS3VideoPMVC;

    // Register Mediators
    facade.registerMediator( new PlayerMediator( app ) );
    }

    >> How did the method find the class CS3VideoPMVC even w/o importing it?

    var app:CS3VideoPMVC = note.getBody() as CS3VideoPMVC;

  16. Posted June 5, 2008 at 1:59 pm | Permalink

    Hi Joel,

    This is because the CS3VideoPMVC lives in the default package, all classes based there are not required for import, HTH :)

  17. Posted June 7, 2008 at 4:30 pm | Permalink

    Thank you.

  18. Joel
    Posted June 10, 2008 at 7:40 am | Permalink

    This is because the CS3VideoPMVC lives in the default package, all classes based there are not required for import, HTH :)

    >> I see. I thought package ownership is strict (i.e. classes on com.pack1.subpack doesn't "live" relative to com.pack1 ..

  19. Joel
    Posted June 10, 2008 at 7:47 am | Permalink

    Thank you Sir :)

  20. Posted July 20, 2008 at 1:03 pm | Permalink

    Hey all,

    PureMVC is definitely lacking tutorials, so I’ve done my bit to help out by writing one :)

    Check it out at http://www.actionscriptdeveloper.co.uk/puremvc-tutorial-flex-puremvc-jabber-and-xiff-3-introduction/

    Enjoy,

    Dave
    http://www.actionscriptdeveloper.co.uk

  21. Posted July 22, 2008 at 3:29 pm | Permalink

    Hi Simon, thanks a ton for taking the time to share your expertise of PureMVC and proper OOP! I have a noob question for ya.. when you call super(viewComponent); from the PlayerMediator constructor, how does Mediator differentiate between parameters? I see Mediator takes two, mediatorName:String and viewComponent:Object - I can see that their dataTypes match what is going on but there is no call to that first string parameter. I'm sure this is a compiler thing that is makes perfect sense to you guys, but its rather abstract to me at this point. Would someone please explain how the compiler knows to skip the first argument and move onto the second? Thank you much for your time!

  22. Posted July 22, 2008 at 3:53 pm | Permalink

    Heh heh its much simpler than that mate and your not going loopo on this one, this demo uses the pre V2 PMVC release :) V2 brought in the two arguments NAME and viewComponent :) NAME is the static const declared as the reference for the Mediator and the viewComponent is as before in pre V2. So your super statement should look like this:

    super( NAME, viewComponent );

    Sorry, my bad really I should get my self round to updating this app!

  23. Posted July 22, 2008 at 5:04 pm | Permalink

    AH, sweet! Thanks Simon - I hadn't actually got to the point of writing it up and trying to compile against my version so I'm glad I asked. I was thinking "wow, have I been ambivalent to some vague caveat with actionscript arguments this whole time or what?!"... I'm glad to hear I might still be "getting it"... Best regards,

  24. Posted September 9, 2008 at 12:18 pm | Permalink

    Very useful and understandable article, many thanks to author!

  25. Posted October 8, 2008 at 3:07 am | Permalink

    It works well, thanks very much, I am very fond of make SWF, I will make our flv player onto web and use easily. I learn much from you!

  26. Posted June 1, 2009 at 12:08 pm | Permalink

    Hi

    nice content..
    thanx man for sharing

  27. eco_bach
    Posted October 30, 2009 at 4:16 am | Permalink

    Nice example, however I think you miss one key point of PureMVC, portability of view components.
    I would argue that all the logic for the flv player to be contained within the view component itself.

  28. Posted November 2, 2009 at 5:17 pm | Permalink

    Well thats the beauty of this framework, really its totally up to you how you use it. I personally hate having to dip back into the View repeatedly and would keep logic most definitely out of the view. Most of my players have logic handled differently, whether it be controls acting/responding differently dependent on media handling i.e. Akamai or FMS etc, or various other event response's throughout the application. Also keeping all logic in the View will actually make it less portable, if thats how you suggest handling it then I would be more inclined to built the player as a swc and use that in various applications but the limitations will soon arise in my opinion.

    This is just my perspective, others can argue for and against but like I said, its good to have the flexibility to use it how you so choose!

  29. Posted December 28, 2009 at 5:06 pm | Permalink

    nice example, i prefer having more control over everything that is going on, an flv player is a relatively simple task, i don't really see the value in splitting it up so much.

  30. Posted December 28, 2009 at 6:13 pm | Permalink

    Cheers Tad,

    This was simply an example into the framework usage in a familiar flash based application. An flv player is as simple or complicated as you want or need it to be at the end of the day. The average joe developer out there may only need to stick in a flvplayback component and be done with it. However, most of my client video apps involve way more logic and splitting this up enables more flexibility in my application, just standard OOP practice, nothing fancy (wanna see extensibility and division of logic then check under the hood of Jeroen Wijering JW player ;) ). TBH though this ain't even split up this much, navigation separated from the video view, and a couple of proxies for video control and streaming, I don't really see this as overkill. Now the beauty is if you wanted to rip out the flvplayback and add you own custom component your in a simple seat to drive on to accomplish this.

6 Trackbacks

  1. By PureMVC FLV Player « The Algorithmist on January 17, 2008 at 12:28 pm

    [...] Check out Simon Baily’s ‘How to Build a Simple FLV Player in Flash and Flex using the PureMVC Framework.’ [...]

  2. [...] to my previous tutorial I want to detail another way into a Flash CS3 application with PureMVC. In the above tutorial I [...]

  3. By PureMVC Links « The Algorithmist on January 22, 2008 at 2:51 pm

    [...] FLV Player with PMVC [...]

  4. [...] on from my last PureMVC tutorial for Flash CS3 I have written a next step tutorial on how to build and implement a Proxy to the FLV player to [...]

  5. [...] have blogged recently about how to build a simple flv player in flash and flex using PureMVC and thought I would extend the functionality to the player by adding the ability to retrieve a [...]

  6. [...] How to Build a Simple FLV Player in Flash and Flex using the PureMVC Framework [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>