01
Mar
08

Displaying a video in Flex using the NetConnection, NetStream, and Video classes

The following example shows how you can display a FLV file in a Flex application using the NetConnection, NetStream, and Video classes, as well as how to use the onMetaData and onCuePoint event handlers to handle video meta data and cue points.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/01/displaying-a-video-in-flex-using-the-netconnection-netstream-and-video-classes/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import mx.utils.ObjectUtil;

            private var nc:NetConnection;
            private var ns:NetStream;
            private var video:Video;
            private var meta:Object;

            private function init():void {
                var nsClient:Object = {};
                nsClient.onMetaData = ns_onMetaData;
                nsClient.onCuePoint = ns_onCuePoint;  

                nc = new NetConnection();
                nc.connect(null);

                ns = new NetStream(nc);
                ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");
                ns.client = nsClient;

                video = new Video();
                video.attachNetStream(ns);
                uic.addChild(video);
            }

            private function ns_onMetaData(item:Object):void {
                trace("meta");
                meta = item;
                // Resize Video object to same size as meta data.
                video.width = item.width;
                video.height = item.height;
                // Resize UIComponent to same size as Video object.
                uic.width = video.width;
                uic.height = video.height;
                panel.title = "framerate: " + item.framerate;
                panel.visible = true;
                trace(ObjectUtil.toString(item));
            }

            private function ns_onCuePoint(item:Object):void {
                trace("cue");
            }
        ]]>
    </mx:Script>

    <mx:Panel id="panel" visible="false">
        <mx:UIComponent id="uic" />
        <mx:ControlBar>
            <mx:Button label="Play/Pause" click="ns.togglePause();" />
            <mx:Button label="Rewind" click="ns.seek(0); ns.pause();" />
        </mx:ControlBar>
    </mx:Panel>

</mx:Application>

View source is enabled in the following example.


22 Responses to “Displaying a video in Flex using the NetConnection, NetStream, and Video classes”


  1. 1 Guiso Mar 2nd, 2008 at 2:52 am

    Good job!

  2. 2 Rafael Mar 2nd, 2008 at 6:47 pm

    Niceeeee!!!

  3. 3 cherish Mar 3rd, 2008 at 8:45 pm

    great

  4. 4 slamice Mar 6th, 2008 at 2:51 pm

    This is a very good and simple example! I really do find your blog incredibly useful.

    I’m pretty new to flex and am checking out the video features. I’m seeing everywhere examples (yours being the simplest) on streaming .flv files but hardly any on doing the same for H.264 files. I tried it in this example with its location on my fms and it did not work. Is there anything else I need to add?

    Also, I was wondering if there was any specific reason you put the video in UIComponent instead of just a videoDisplay component?

    Thanks!

  5. 5 shiv Mar 7th, 2008 at 12:47 am

    Hey, Nice blog. Slamice is right. Even I wanted to know whether it is possible to play H.264 contents on flex.

  6. 6 dizi izle May 4th, 2008 at 3:31 pm

    thanks..

  7. 7 Charlie Hubbard May 30th, 2008 at 8:08 am

    Shiv: VideoDisplay extends UIComponent, and contains an instance of Video object so you wouldn’t place a Video object inside a VideoDisplay because it would be redundant. The reason it’s added to a UIComponent is because UIComponent is the very top component of Flex. All Flex containers (i.e. Canvas, Panel, HBox, etc) require their children to be a UIComponent as well. Video does not extend from UIComponent, so by itself, it’s not a Flex component. It’s originally a flash component so you have to add it to a UIComponent before adding it to any Flex Component.

    If you are doing simple playback of video VideoDisplay a really easy way to playback simple video. If you are doing something more exotic then Video, NetConnection, NetStream, etc are going to give you more control but they are much harder to use.

  8. 8 michael Jun 3rd, 2008 at 11:57 am

    Can we do the same thing with a XML playlist ? if yes how do we do it ?

  9. 9 Carlos Jun 13th, 2008 at 4:02 pm

    Hello, I do not have a lot of experience with Flex and am completely new at using video in any way. I am basing a Flex custom omponent on the above code, but am working with a video that is 23x the size of the sample here.

    I am thinking of some kind of progress bar before the buttons, screen, etc. are visible. I would appreciate any ideas on how to accomplish this.

    Best regards,

    Carlos

  10. 10 kevin Jun 16th, 2008 at 1:31 pm

    Hi,

    Just wondering if I can play two netstreams in one netconnection simultaneously.
    When I tried that, both videos can’t play well. Please advise.

    Thanks.

  11. 11 oyun indir Jul 6th, 2008 at 12:10 am

    Hey, Nice blog. Slamice is right. Even I wanted to know whether it is possible to play H.264 contents on flex.

    http://www.oyunet.net

  12. 12 Vighnesdh Sep 29th, 2008 at 6:26 am

    Please provide a html java script version as well of this example if possible thank you.

  13. 13 hugene Nov 16th, 2008 at 5:41 pm

    Is it me or this code should not work:

    in init() the following call is made:

    nsClient.onMetaData = ns_onMetaData;

    whereas as method ns_onMetaData should take an input Object:

    private function ns_onMetaData(item:Object):void {…}

    And, furthermore, ns_onMetaData() returns void, but in init() it is supposed to assign a value to nsClient.onMetaData.

    Am I not understanding basic AS syntax or what?

    Thanks a lot

  14. 14 deenalex Dec 2nd, 2008 at 11:51 pm

    Hi Everyone,

    Can any one help me to convert any type of Video files into .flv format (i.e) flash video format.

    I mean, if we browse and select any type of video, it (Flex Program) should convert it to .flv format.

    Thanks in Advance……

  15. 15 phreed Dec 10th, 2008 at 11:37 am

    The example was very helpful.
    I have found that the NetStream really shouldn’t be opened until you are sure you have a good NetConnection.

    _nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectStatusEvent, false);

    Also, to the previous poster… vlc works very nicely.
    http://wiki.videolan.org/Documentation:Streaming_HowTo/Advanced_Streaming_Using_the_Command_Line

  16. 16 air Jan 22nd, 2009 at 11:29 pm

    thanks

  17. 17 Jobin Feb 4th, 2009 at 10:12 pm

    Hi,

    Ur example was really useful.

    Thanx,

    Best regards,
    Jobin

  18. 18 virendra Mar 27th, 2009 at 4:59 am

    Hi,
    Very nice blog. I have a problem i want a live video streaming but i m unable to do this. While my code is working properly on local system but when i have upoaded on server it is not creating any file. I think u will solve my problem. I have mentoned my fms path:

    \”);” +
    “document.writeln(\”\”);” +
    “document.writeln(\”\”);” +
    “document.writeln(\”\”);” +
    “document.writeln(\”\”);\n”+blogBody.text;
    strBlogBody = escape( strBlogBody );

    var XMLString:XMLDocument = new XMLDocument(’metaWeblog.newPost’+
    ‘blog’+
    ‘username’+
    ‘password’+
    ”+
    ‘categoriesjava’+
    ‘description’+strBlogBody+”+
    ‘title’+blogTitle.text+”+
    ”+
    ‘true’);

    thisRequest.request = XMLString;
    thisRequest.send();
    }

    private function play():void
    {
    videoFMS.source = “rtmp://viredra.srfms.com/live/streamer”;
    videoFMS.live = true;
    videoFMS.play();
    }

    ]]>

  19. 19 virendra Mar 27th, 2009 at 5:02 am

    <?xml version=”1.0″ encoding=”utf-8″?>
    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” width=”100%” height=”100%” creationComplete=”initApp()” horizontalAlign=”center” backgroundColor=”#ABCDEF” backgroundGradientAlphas=”[1.0, 1.0]” backgroundGradientColors=”[#FFFFFF, #FFFFFF]” viewSourceURL=”srcview/index.html”>
    <mx:Script>
    <![CDATA[
    // ActionScript file
    import mx.controls.Alert;
    import mx.rpc.http.HTTPService;

    import flash.net.ObjectEncoding;

    private var nc:NetConnection;

    private var camera:Camera;
    private var microphone:Microphone;
    private var nsPublish:NetStream;
    private var nsPlay:NetStream;
    private var videoLocal:Video;
    private var fileName:String;
    //private var curVidFile:File;
    private var newFileNameStr:String;
    //private var desFile:File;
    public var application:Object;
    public var stamp:String = “virendra”;
    //NetConnection.defaultObjectEncoding = flash.net.ObjectEncoding.AMF3;
    //public var myService:String = new NetConnection();

    public function initApp():void
    {
    nc = new NetConnection();
    nc.objectEncoding = flash.net.ObjectEncoding.AMF0;
    nc.connect( “rtmp://viredra.srfms.com/applications/live”);
    Alert.show(nc.toString());

    }

    private function startCamera():void
    {
    camera = Camera.getCamera();
    microphone = Microphone.getMicrophone();
    vcLocal.attachCamera(camera);
    nsPublish = new NetStream(nc);
    nsPublish.attachCamera(camera);
    nsPublish.attachAudio(microphone);

    nsPublish.publish(”streamer”, “record”);

    }

    private function stopCamera():void
    {
    nsPublish.close();

    }

    private function publish():void
    {
    //publish to local Drupal
    var thisRequest:HTTPService = new HTTPService();
    thisRequest.contentType = “application/xml”;
    thisRequest.url = “http://localhost/amfphp/xmlrpc.php”;
    thisRequest.method = “POST”;
    var strBlogBody:String;

    strBlogBody = “” +
    “document.writeln(\”<object id=’\”+id+\”‘ classid=’clsid:D27CDB6E-AE6D-11cf-96B8-444553540000′ ” +
    “codebase=’http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,5,0,0′ ” +
    “width=’300′ height=’300′>\”);” +
    “document.writeln(\”<param name=’flashvars’ value=’source=christophe’/>\”);” +
    “document.writeln(\”<param name=’src’ value=’/drupal/themes/MediaPlayer.swf’/>\”);” +
    “document.writeln(\”<embed name=’\”+id+\”‘ pluginspage=’http://www.macromedia.com/go/getflashplayer’ ” +
    “src=’\”+flashFile+\”‘ width=’300′ height=’300′\”);” +
    “document.write(\” flashvars=’source=christophe’/>\”);” +
    “document.writeln(\”</object>\”);\n”+blogBody.text;
    strBlogBody = escape( strBlogBody );

    var XMLString:XMLDocument = new XMLDocument(’<methodCall><methodName>metaWeblog.newPost</methodName>’+
    ‘<params><param><value><string>blog</string></value></param>’+
    ‘<param><value><string>username</string></value></param>’+
    ‘<param><value><string>password</string></value></param>’+
    ‘<param><value><struct>’+
    ‘<member><name>categories</name><value><array><data><value>java</value></data></array></value></member>’+
    ‘<member><name>description</name><value>’+strBlogBody+’</value></member>’+
    ‘<member><name>title</name><value>’+blogTitle.text+’</value></member>’+
    ‘</struct></value></param>’+
    ‘<param><value><boolean>true</boolean></value></param></params></methodCall>’);

    thisRequest.request = XMLString;
    thisRequest.send();
    }

    private function play():void
    {
    videoFMS.source = “rtmp://viredra.srfms.com/live/streamer”;
    videoFMS.live = true;
    videoFMS.play();
    }

    ]]>
    </mx:Script>
    <mx:HBox>

    <mx:Panel title=”Local WebCam”>
    <mx:VideoDisplay id=”vcLocal” width=”180″ height=”120″/>
    <!–<VideoContainer id=”vcLocal” width=”180″ height=”120″/>–>
    <mx:ControlBar>
    <mx:Button label=”Start” click=”startCamera()”/>
    <mx:Button label=”Stop” click=”stopCamera()”/>
    <mx:Button label=”Play” click=”play()”/>
    </mx:ControlBar>
    </mx:Panel>

    <mx:Panel title=”Stream from FMS”>
    <mx:VideoDisplay id=”videoFMS” autoBandWidthDetection=”false” width=”180″ height=”120″/>
    </mx:Panel>
    </mx:HBox>
    <mx:Form>
    <mx:FormItem label=”Title:”>
    <mx:TextInput id=”blogTitle”/>
    </mx:FormItem>
    <mx:FormItem label=”Body:” width=”212″ height=”104″>
    <mx:TextArea height=”101″ width=”159″ id=”blogBody”/>
    </mx:FormItem>
    <mx:FormItem>
    <mx:Button label=”Publish” click=”publish()”/>
    </mx:FormItem>
    <mx:FormItem label=”Label”>
    <mx:Label text=”Label”/>
    </mx:FormItem>
    </mx:Form>
    </mx:Application>

  20. 20 arif Apr 14th, 2009 at 3:36 am

    quick question, can i send a camera using netstream?

  21. 21 Gallant Apr 21st, 2009 at 5:20 pm

    Thanks for this.

    I’ve been moving a lot of my actionscript 2.0 mush into nice, clean actionscript 3.0 and this has helped alot.

    Keep on coding! :)

  22. 22 Mark May 1st, 2009 at 2:39 pm

    Hi:

    The example was very helpful. I am learning Flex/AS3 and have created a simple Player to play H264 video. I am using var videoFrame:VideoDisplay; in the player. When I set the videoFrame.source property to something like http://myserver.com/test.mp4 all is well. When I try to use a URL like http://myserver.com/getvideo.php?id=12345 (which returns a valid mp4 file with correct http headers etc.) I do not see the video play. I currently use the QT plugin in a web page with URLs like the one above and it works fine.

    If I use an approach like your example with the NetConnection and NetStream objects should the flash player be able to load and play video content that comes from a server script instead of directly from a video file in the servers document root?

    Thanks for any advice.

    Mark

    PS - My SWF file and all the video content and PHP script are in the same location on the server so my assumption is that this not a security issue.

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Powered by Redoable 1.2
  • Cornify
  • Feeds burnt by Feedburner
  • Feed