in Actionscript 3

ActionScript 3 QuickTip #2 – FLV Playback

There have been quite a few changes to the way in which you implement a custom FLV player using the NetConnection and NetStream classes in ActionScript 3. You can look at the code here to see the current ActionScript 2 implementation. The ActionScript 3 version starts out the same way by defining the NetConnection object and passing null its connect method. Also the same is the creation of the NetStream object by passing in a reference to the aforementioned NetConnection object.

  1. var nc:NetConnection = new NetConnection();
  2. nc.connect(null);
  3.  
  4. var ns:NetStream = new NetStream(nc);

We can finally create an embedded video object using only code! We previously had to go the library, create the object, and drag it out onto the stage. In ActionScript 3 we simple create the video object just like we do with any class that inherits from DisplayObject. To the constructor we pass in the width and height that we want the video object to be. Finally we need to add the video object to the DisplayList in order to have it rendered to the screen.

  1. var vid:Video = new Video(320, 240);
  2. this.addChild(vid);

Once we’ve created the video object we now need to connect it to the NetStream object. In ActionScript 2 we did this using the attachVideo() method of the Video class. In ActionScript 3 there is now a more-appropriately called method called attachNetStream(). As a side note, If you want to attach a webcam to the video object you would use the new attachCamera() method. Once the NetStream is attached we can begin playing an external FLV the same as before by calling the NetStream.play() method.

  1. vid.attachNetStream(ns);
  2.  
  3. ns.play(“test.flv”);

There have been major overhauls to the way in which you respond to events from the NetStream class. First off, you have to provide a callback function for the onMetaData event or Flash will throw errors at you. You need to create an object that will act as the NetStream’s client for the callback event. Once you have setup the onMetaData function for this object you need to set the NetStream.client property so it knows where to look. If your FLV contains embedded cue points then you will also need to create an onCuePoint function to handle that callback event.

  1. var netClient:Object = new Object();
  2. netClient.onMetaData = function(meta:Object)
  3. {
  4.         trace(meta.duration);
  5. };
  6. ns.client = netClient;

In ActionScript 2 we defined the NetStream.onStatus() event in order to receive status messages. In ActionScript 3 we use the NetStream.addEventListener() method to define a listener function to respond to this event. See the code below for the exact implementation of this new method for handling events.

  1. ns.addEventListener(NetStatusEvent.NET_STATUS, netstat);
  2.  
  3. function netstat(stats:NetStatusEvent)
  4. {
  5.         trace(stats.info.code);
  6. };

Look for more articles in the future regarding the ActionScript 3 video integration. Below is the full code block for implementing FLV playback in ActionScript 3.

  1. var nc:NetConnection = new NetConnection();
  2. nc.connect(null);
  3.  
  4. var ns:NetStream = new NetStream(nc);
  5.  
  6. var vid:Video = new Video(320, 240);
  7. this.addChild(vid);
  8.  
  9. vid.attachNetStream(ns);
  10.  
  11. ns.play(“test.flv”);
  12.  
  13. ns.addEventListener(NetStatusEvent.NET_STATUS, netstat);
  14.  
  15. function netstat(stats:NetStatusEvent)
  16. {
  17.         trace(stats.info.code);
  18. }
  19.  
  20. var netClient:Object = new Object();
  21. netClient.onMetaData = function(meta:Object)
  22. {
  23.         trace(meta.duration);
  24. };
  25.  
  26. ns.client = netClient;

Lee

Write a Comment

Comment

54 Comments

  1. Hi Lee,
    From this tutorial and one before this, Do you mean ‘we must ready for as3′ ?
    You will change the themes of your blog and tutorials to AS3, won’t you?
    For me, AS3 is more complicated than AS2.

    Physica

  2. Hey Lee,

    Thanks for that valuable information, personally I think it makes a lot more sense in AS3 the logic just seems clearer, but that just me.
    Brilliantly layed out for all the vital stuff to get going with video and AS3 ta very much,

    Si

  3. Hi Lee,

    If you want to control the volume, how is it done in AS3? In AS2, you needed an empty MC, and then attach the audio stream to it:

    this.createEmptyMovieClip(“snd”, 0);
    this.snd.attachAudio(this.ns); //attach NetStream
    this.audio = new Sound(this.snd); //Set MC as source
    this.audio.setVolume(80);

    how is this acheived with AS3?

    Thanks

  4. hey guys, this might be a bit unrelated, but do any of u know how to turn off the INSANELY ANNOYING transparency transitions that the new CS3 interface decided to add? u know, as when u switch off to new apps, the interface alphas in and out. stupid/.

  5. Hey Andrew, I scratched my head for awhile about controlling the volume too…

    var st:SoundTransform=new SoundTransform();

    st.volume=0;

    ns.soundTransform=st;

  6. Hi –

    I was wondering if anyone has encountered a problem in AS3 with video playback where the eventListener object for a netStream is no longer recognized once video playback has been paused and unpaused? This is occuring with progressive downloads only. I have a colleague who is encountering this issue, and the only workaround we had was to re-attach the eventListener object when the user decides to unpause the video. thanks

  7. I would like to bundle the player and the flv into a single .swf for easy download purposes – there is content in the .swf that is necessary to understanding the .flv. Is there a good way to create a single file that could be used standalone by both Mac and Windows users?

  8. Do you know of a way to access the netstream object of an flvplayback component? I prefer the ease of the components, but I can’t access the bufferLength property on an flvplayback video player :(

  9. How would you go about creating a cue point listener to integrate with this method? Also to run 2 screens at once would I have to create a new instance of vid or of everything?

  10. I would like to rely on metadata to determin the height and width of the video player im creating, is it possible to change the width/height after creating the video?

    ex.
    var vid:Video = new Video();
    this.addChild(vid);
    vid.height = preferredHeight;
    vid.width = preferredWidth;

  11. Is it possible with AS3 to have two FLV’s playing simultaneously while controlling them both with One set of controls? Can I use the components to create the controls, or do I have to manually go in and change something in the AS?

    Thanks much!

  12. Hello, Lee.

    Thank you so much for taking the time to create and publish your tutorials. They have helped me immensely.

    I would like to know if you have a tutorial specifically geared toward playing two video files (one: atlantis.flv, the other, ticker.SWF rss news ticker) simultaneously. I would like to “lay” one file–the ticker, with price information–over the bottom of the atlantis.flv. I haven’t seen anything specific in your AS3 or Video Basics tutorials regarding this issue.

    Thank you very much for your time.

    –john

  13. Browser Effects Streaming Behavior (Downloads Whole .FLV before Playback)

    Hi, I just posted this question over at

    http://www.quip.net/blog/2007/flash/how-to-load-external-video-as3

    but I thought I’d ask here while I was at it.

    I am using this method to display video, but when delivered in a browser the behavior changes.

    Everything works fine from the flash ide, or when running a swf. The progressive download works great, and the video begins playing while the flv is still loading

    However, if I open it in a browser, It will always download the entire .flv before playback begins.

    I have to deliver some quite long videos, so this is a real issue. The behaviour is the same when the .html and .fla is online, reading from a relative folder.

    I am making sure to use:

    nc.connect(null);

    …to indicate a progressive download, as described above.

    Has anyone had this problem?

    Thanks,

    -Lee (Bergman)

  14. OK, this turned out to be something strange and probably very rare.

    I had been playing with BulkLoader (which is great BTW):

    http://www.stimuli.com.br/trane/2007/nov/25/loading-reloaded/

    ..to load my videos but had decided not to use it for now. However I was still adding my videos to BulkLoader during my xml read function using bLoader.add()

    It did not occur to me right away that this might effect things, but when I removed that line everything performed as expected. I doubt this will come up for anyone very soon, but I thought I’d better add this follow up.

  15. Hi…
    I am putting together a video player and used the methods described in this tutorial and the video counterpart to create it. It was working fine on my desktop (windows xp), and then when opened to edit on my laptop (vista), the flv no longer plays and I am left with a blank space in its place.

    Might I have some settings not configured properly in Flash on my laptop or is this one of the reasons Lee finally switched to a Mac?

    Any help…..as always thank you in advance!

  16. HAHAHA … yes, you need to use the SoundTransform class to modify the sound in as3. once again, (like most of the migrations of this kind) itt makes WAaaaay more common sense and is very easy to implement in a custom flv player.

    DONT, however, think you’ve got it all sorted out like i did and write in :
    st.volume=100; !!!!!!!!!

    (remember that these new values in flash are 0-1, not 0-100.

    VERY FREAKIN Loud sound!
    Rick

  17. Have tried connecting to a rtmp server but keep getting “Error #2126: NetConnection object must be connected.” Any ideas ?

  18. Have tried connecting to a rtmp server but keep getting “Error #2126: NetConnection object must be connected.” Any ideas ?

    Correct email !!

  19. Is it possible to add cue points on the fly? It seems like this should be possible but I can’t find it anywhere. if someone could point me in the right directions, it would be very appreciated.

  20. Hi Lee,
    i have encountered a new problem,
    i m developing somthing which need to play many streaming in a single web page.

    while playing, normally I get the “netstream.reset” and after that “netstream.play” status, But after play status sometimes there is nothing in video object.

    help me to check my video object, if there is anything playing or not.

    all suggestion are welcome at nitin.arora@appulse.com

    thanks in advance

  21. Thanks for the help. I was really only hung up on the abnormality of the metadata handling. But this helped me out greatly! thanks again.

  22. also try using the FLVPlayBack method if this doesn’t work. im not a pro at AS3 but thats wat im using and it works fine for me.. and this way u can use the pre defined flash skins if you want.

    vid.source = “flashvideo.flv”;
    vid.skin = “SkinOverPlaySeekFullscreen.swf”;
    vid.scaleMode = StageScaleMode.EXACT_FIT;
    vid.skinBackgroundColor = 0x333333;
    vid.skinBackgroundAlpha = 1;
    vid.skinAutoHide=true;
    vid.bufferTime=3;
    vid.height=282;
    vid.width=498;
    vid.x=390;
    vid.y=185;
    stage.addChild(vid);

  23. help me. I’m trying to load a video but just load the sound

    package {
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.media.Video;
    import flash.display.Sprite;

    public class video extends Sprite {
    public var videoConnection:NetConnection;
    public var videoStream:NetStream;
    public var myVideo:Video;
    public var elVideo:String;

    public function video(elVideo:String) {

    myVideo=new Video(120,120);
    videoConnection=new NetConnection();
    videoConnection.connect(null);
    videoStream=new NetStream(videoConnection);
    videoStream.client=new Object();
    videoStream.play(elVideo);
    myVideo.attachNetStream(videoStream);
    addChild(myVideo);
    }
    }
    }

  24. No video, only sound (guess it’s the same problem as the post above…). Media is loaded (and sound playing), but no video is shown. Please help.

  25. 1.
    var nc:NetConnection = new NetConnection();
    2.
    nc.connect(null);
    3.

    4.
    var ns:NetStream = new NetStream(nc);
    5.

    6.
    var vid:Video = new Video(320, 240);
    7.
    this.addChild(vid);
    8.

    9.
    vid.attachNetStream(ns);
    10.

    11.
    ns.play(“test.flv”);
    12.

    13.
    ns.addEventListener(NetStatusEvent.NET_STATUS, netstat);
    14.

    15.
    function netstat(stats:NetStatusEvent)
    16.
    {
    17.
    trace(stats.info.code);
    18.
    }
    19.

    20.
    var netClient:Object = new Object();
    21.
    netClient.onMetaData = function(meta:Object)
    22.
    {
    23.
    trace(meta.duration);
    24.
    };
    25.

    26.
    ns.client = netClient;

    I’m getting those uggly numbers when copying. Irritates me.

  26. Yo, I found the FLVPlayBack bufferlength and netstream.

    var flvpb:FLVPlayBack = video_comp; // FLVPlayback component on the timeline for example with identifier name video_comp;

    var vp:VideoPlayer = VideoPlayer( flvpb.getVideoPlayer(flvpb.activeVideoPlayerIndex) ); // active video player

    var ns:NetStream = NetStream(vp.netStream); // netstream

    var bl:Number = ns.bufferLength;// buffer length duh…

  27. Can you please direct me on how to implement AS 3.0 to attach a live video stream using the Adobe Flash Media Encoder and Adobe Flash Media Server and camera on my local network?

  28. What happens if your audio is in the video .flv format? Would you still use this method? To use the sound classes, do you need your file format to be in .mp3?

    Thanks!

  29. Hey!
    I have been trying to stream a live video with the FLVPlayback and ActionScript 3.0. However, after hours and hours of work it still does not work. Can someone please help!!

    Below is the code:

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

    var ns:NetStream = new NetStream(nc);

    var flvPlayerlive:FLVPlayback = new FLVPlayback();

    stage.addChild(flvPlayerlive); //or this.addChild

    //setting properties of FLVPlayback videos
    flvPlayerlive.width=320;
    flvPlayerlive.height=240;
    flvPlayerlive.x=5;
    flvPlayerlive.y=-55;
    flvPlayerlive.skinBackgroundColor = 0x666666;
    flvPlayerlive.skinBackgroundAlpha = 100;

    flvPlayerlive.autoPlay = false;

    flvPlayerlive.skin = “skin/SkinUnderPlayFullScreen.swf”;
    flvPlayerlive.isLive = true;
    flvPlayerlive.source(“rtmp://localhost/livecast/”);

    flvPlayerlive.attachNetStream(ns);
    ns.play(“abc.flv”);

    Two error messages:
    1195: Attempted access of inaccessible method source through a reference with static type fl.video:FLVPlayback.
    1061: Call to a possibly undefined method attachNetStream through a reference with static type fl.video:FLVPlayback.

  30. Hi Tina, the errors that are being shown are because you are trying to define some parameters in the wrong way. first you need to declare source like this:

    flvPlayerlive.source = “rtmp://localhost/livecast”);

    and you can’t attach a netStream to a FLVPlayback component, you can do that to a Video instance or flash.media.Video, and if you are broadcasting a live video you need to do a connection to the FMS server so you should not be passing “null” to the NetConnection Object you need to define the path to your local FMS host application, you could easly do all this avoiding the use of FLVPlayback component since it is a liveStreaming you just need to use the flash.media.Video, and set it properly.

  31. I wish i could edit the last post, in the assignment of the source should be without parentesis

    player.source = “sourceURL”;

  32. Thank you very much for your reply. I can’t believe that it was a syntax error. I spend ages on that and even my friend didn’t spot that. Well, I’m still new to all that ;)

  33. Hello,

    what would be the correct way to approach having an eventListner gotoAndPlay some frame after the FLV finishes playing?

    Thank you much

  34. In this last example: What if you want to put the video as a fullscreen?

    I´m trying something like:

    var vid:Video = new Video(stage.stageWidth, stage.stageHeight);
    But doesn´t work if user changes screen

  35. Please help!

    I’m new in flash media server… just learning the tricks on development server.

    My first day was very positive. I used same code like Lee here and it works fine with flv files. And easy to understand how it works. But later i tried to stream mp3 audio with similar code (but without the video var and stuffs like this)… and it was big surprise.

    Tutorials say it is the same, i just have to reference the file like this: “mp3:filename”. But server answers: stream not found. I tried “mp3:filename.mp3″ and “filename.mp3″ too… same answer.

    When i write only “filename”, server starts to play, i can stop and pause the stream too, but nothing happens: no sound, no data.

    What can be the problem?
    Maybe problem is not with my as3 code wich works fine with flv, but on server side? I just put mp3 files to vod (vod/media), where flv files are.

    thanks,
    Arnold

    sorry for my not perfect english

  36. I’m having the same problem mentioned on comment #20. I am setting up my NetConnection and connecting to null and then trying to load my video (which resides on the same host, but in a sub-directory of where the swf is located). The video does not start playing however until it is completely loaded (which takes a while since it is a 50 meg file)

    Obviously I do not want to wait for the user to download the entire video before starting playback so this is perplexing me.

    The video is actually not a .flv but a H.264 .mov. Would that affect the player being able to play it before it is fully downloaded?

  37. I loaded my video through the given code (worked great, nice job! thanks!), but I’m trying to add controls (pause/play, scrubber, volume), and they aren’t visible. I think they are being put on a layer below that of the video (I have them manually put on the stage right now, whereas the AS [in a top level ‘actions’ layer] is dynamically calling the video).
    Can anyone help me push the video to the bottom layer and pull the controls up to the top layer?
    Thanks
    J

  38. Hi,

    Can anyone help me, i keep getting this error NetStream.Play.StreamNotFound and as far as i can tell there is nothing wrong with my code.

    Code:
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.media.Video;

    stop();

    // Create a NetConnection object:
    var nc:NetConnection = new NetConnection();
    // Create a local streaming connection:
    nc.connect(null);
    // Create a NetStream object
    var ns:NetStream = new NetStream(nc);

    // Attach the NetStream video feed to the Video object:
    myVideo.attachNetStream(ns);

    var chec:Boolean = true;

    mc_stop.addEventListener(MouseEvent.CLICK, stops);
    function stops(event:MouseEvent):void{

    stop();
    chec = true;
    ns.seek(66);
    mc_play.buttonMode = false;
    mc_play.gotoAndStop(1);
    }

    // play button & pause button
    mc_play..addEventListener(MouseEvent.CLICK, plays);
    function plays(event:MouseEvent):void{

    if (mc_play.buttonMode == false)
    {
    mc_play.buttonMode = true;
    mc_play.gotoAndStop(2);

    }
    else
    {
    mc_play.buttonMode = false;
    mc_play.gotoAndStop(1);

    }
    ns.pause();
    if(chec == true)
    {
    ns.play(“Wedding.flv”);
    mc_play.buttonMode = true;
    mc_play.gotoAndStop(2);
    chec = false;
    }
    }

    ns.addEventListener(NetStatusEvent.NET_STATUS, netstat);

    function netstat(stats:NetStatusEvent)

    {
    trace(stats.info.code);

    }

    var netClient:Object = new Object();

    netClient.onMetaData = function(meta:Object)

    {

    trace(meta.duration);

    };

    ns.client = netClient;

  39. Hi Lee,

    I am trying to load 2 ext file(one .flv file & the other .swf file) & play them concurrently but the .flv video playback lag when the .swf file was loaded & played.

    I will load the .flv file first & when the .flv play for 2 secs, I load .swf file & play. Then I’ll see the video of the .flv become lagging until the .swf finish playing.

    var mLoader:Loader = new Loader();
    var mRequest:URLRequest = new URLRequest(“logo.swf”);

    loadVid();
    Tweener.addTween(mc24, {delay:2, onComplete: startLoad});

    function loadVid()
    {
    contents.myFLV.source = “video.flv”;
    contents.myFLV.addEventListener(VideoEvent.COMPLETE, videoFinished);

    }

    function videoFinished(event:Event)
    {
    contents.myFLV.play();
    }

    function startLoad()
    {
    mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
    mLoader.load(mRequest);

    addChild(mLoader);
    }

    function onCompleteHandler(loadEvent:Event)
    {
    addChild(loadEvent.currentTarget.content);
    }

    I’m not sure is my coding giving me this problem or is the size of the video & swf file.

    Size of vieo.flv is about 5mb & logo.swf is about 104kb.

  40. Hi there lee, I´m trying to move on to AS3, i have this simple function but I dont know how can I achieve the same purpose without AS2 could you help me out…?

    var nc:NetConnection = new NetConnection();
    nc.connect(null);
    var ns:NetStream = new NetStream(nc);
    video.attachVideo(ns);

    var my_sound:Sound = new Sound();
    my_sound.onLoad = function(success:Boolean)
    {
    if (success)
    {
    ns.play(“video_1.flv”);
    ns.onStatus = function(info:Object)
    {
    if(info.code == ‘NetStream.Play.Stop’)
    {
    ns.play(“video_2.flv”);
    }
    }
    }
    };

  41. I´ve posted yesterday how can I achieve with as3 my old as2 script, I´ve managed that, I´m running into a huge problem, doesnt matter if AS2 or AS3, the latest release of flash player 10.1, all that script and the courses that I´ve made using the flv´s and external mp3 are now making the browser crash(any browser with the 10.1 plugin), and worst of all I dont have any idea why is that happening, could you help me out…? My basic script is above…

  42. Hi Lee, has been 5 days now but I figure out how can I use, the only thing that´s now working it´s the sound, it kind start when the mp3 finish the loading, and I want that start when the sound “start” to play, here´s what I research:

    ns.addEventListener(NetStatusEvent.NET_STATUS, detectEnd);
    function detectEnd(myevent:NetStatusEvent):void
    {
    switch (myevent.info.code)
    {
    case “NetStream.Play.Stop”:
    ns.seek(0);
    break;
    }
    }

    var mySound:Sound = new Sound();
    mySound.load(new URLRequest(“audio/sistema de caixa.mp3″));
    mySound.addEventListener(Event.OPEN, doStart);
    function doStart($evt:Event):void
    {
    ns.play(“character_rest.flv”);
    ns.addEventListener(NetStatusEvent.NET_STATUS, netStatTalk);
    function netStatTalk(talkStat:NetStatusEvent)
    {
    if(talkStat.info.code==”NetStream.Play.Stop”)
    {
    ns.play(“character_talk.flv”);
    }
    }
    }

    mySound.addEventListener(Event.SOUND_COMPLETE, doSoundComplete);
    function doSoundComplete($evt:Event):void
    {
    ns.play(“character_going_rest.flv”);
    ns.addEventListener(NetStatusEvent.NET_STATUS, netStatRest);
    function netStatRest(restStat:NetStatusEvent)
    {
    if(restStat.info.code==”NetStream.Play.Stop”)
    {
    ns.play(“character_rest.flv”);
    }
    }
    }