How to Control Video (FLV) without a Component
This earlier post, “How to Load External Video (FLV),” is one of the most popular on this blog, judging by the number of comments. Just the other day, someone named Enrique thanked me for the sample code, but asked if there was a way to control the FLV file once loaded, since the file is handled without the use of the Media or FLVPlayback Components. It’s a good question, so let’s take a look at how to accomplish the goal.
An answer, short and sweet
After typing the code suggested in the other article, type the following ActionScript into a frame of your scripts layer:
// Code from the other article
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play("externalVideo.flv");
// New code ... assumes a button symbol with
// the instance name shown
btnPausePlay.onRelease = function() {
ns.pause();
}
How’s that for short and sweet?!
How it works
This answer comes from a quick glimpse again at the NetStream class. We’re already using the NetStream.play() method, in fact. Here, we’re simply using the NetStream.pause() method, applied to the ns variable, which is our instance of the NetStream class.
The first time this method is called, it pauses play. After that, the method acts as a toggle — unless the optional parameter is supplied. If you want two buttons, rather than a toggle, supply that parameter.
btnPause.onRelease = function() {
ns.pause(true);
}
btnPlay.onRelease = function() {
ns.pause(false);
}
In the above example, the pause button invokes the NetStream.pause() method, as before, but this time it supplies the optional flag parameter. If true is supplied, the video is paused, regardless of it’s already paused. If false is supplied, the video is played from where it was stopped. If already playing, it keeps on playing.
Experiment with the NetStream.close() and NetStream.seek() methods to stop playing altogether (different from pausing) and to jump to already-loaded portions of a video stream.
October 24th, 2006 at 4:39 am
i’ve read both this post and the earlier FLV related post, and did some testing of my own.
i’ve used both video object (together with the netConnection/netStream), and the FLV playback component. the conclusion i can’t avoid is that when using the video object the video playback was far from being smooth, while viewing the same file with the FLV playback component, after waiting for few seconds (less than 5) the playback was smooth as a baby’s behind
i did the tests with 2 FLV files i’ve uploaded to my server - one 3Mb and the other more than 7Mb (and yes - i’ve deleted them from the cache after every test…). when using the video object i set the buffer time to 5 (’my_ns.setBufferTime(5)’), and when using the FLV playback component, i’ve left the buffer time as is (the defaul in the component properties is 0.1).
needless to say, that even if i don’t use the component’s UI, it still comes with a lot more properties i can use than what the video object has to offer…
October 24th, 2006 at 8:26 am
eRez,
Interesting!
— when I have some time (if I remember!), I’ll try to run the same sort of experiments. Discrepancies like this always interest me, because these things are not often apparent at the outset. Thanks for the feedback!
October 24th, 2006 at 9:06 am
David,
about that ‘unavoidable conclusion’ i had in my previous post - well, i have some second thoughs…
when i said that i deleted the files from my cache after every test, what i actually did wasn’t using the IE ‘tools–options–delete files’ button, but deleting the files (1.flv, 2.flv) from ny ‘temporary internet files’. however, if i closed the flash’s preview window before the file has completely downloaded, that flv file wasn’t found in that folder, and on my next test the download began from where it stopped on the last time.
i wonder where this incomplete file is hiding - on your free time try this test: use your IE ‘delete files’ button to clear your cache, now open the ‘temporary internet files’ folder, and you’ll find there only some cookies - lets say total of 100 files. now start downloading video directly from flash and stop it before it ends - surprisingly you’ll still find exactly 100 files in your ‘temporary internet files’, but on your next download (of the same file) the download won’t start from 0 but from where you’ve stopped - so as i said: where that incomplete file is hiding???
the bottom line is that there seem to be no major difference concerning download time between the video object and the flv playback component.
November 22nd, 2006 at 7:29 pm
is there a way to control the sound of an external flv?
November 24th, 2006 at 9:08 am
Hi, is there a way to swap a graphic for the button when it is in the “pause” state, (attachMovie for instance?). I may be betraying my ignorance regarding actionscript as I am quite the newbie.
November 27th, 2006 at 2:28 am
To the last two …
Aaron,
You can control the volume of the whole SWF itself, which will naturally affect the volume of loaded video (see “How to Toggle Sound Globally” and “Understanding the Sound Constructor“). But what you’re after, I believe, is the
MovieClip.attachAudio()method.David,
Flash gives you a handful of ways to accomplish this goal. Pulling one solution out of a hat, you could make the button a movie clip symbol. Then use
MovieClip.gotoAndStop()to send that clip’s timeline to whatever frame represents the desired graphic. (Note that theMovieClipclass and theButtonclass share a number of mouse-related events events.)December 18th, 2006 at 4:05 am
Hi Dave,
I currently have a pretty sophisticated video application currently in use that loads external video, but the video and audio files we use are imported using MovieClip.loadmovie() as they are all .swf files.
Our application does a lot of sophisticated frame specific playback control etc. taking advantage of frame-specific movieclip control such as gotoandplay(), gotoandstop() and getting frame specific feedback such as _currentframe.
Can I embed the Video Object into a Movie Clip in my project fla, and then control the flv videos I’ve loaded via your method (or any other) using our Movie Clip controls?
[Macromedia says: “You can apply the following actions to imported video objects in movie clips: goTo, play, stop, toggleHighQuality, stopAllSounds, getURL, FScommand, loadMovie, unloadMovie, ifFrameLoaded, and onMouseEvent. To apply actions to a video object, you must first convert the video object to a movie clip…” BUT CAN YOU apply these same actions to a video object when the flv is loaded dynamically from the server?]
If NOT possible to do this, netstream.seek does not seem to be able to give us the precise frame level control we now have. As as far as I can tell, you can only put integers into the FLVplayback behaviors, seekPercent() or seekSeconds(). Also, value of “time” in netstream seems to give only rounded fully seconds, no where near as accurate as _currentframe.
December 18th, 2006 at 5:57 pm
John D,
To-the-frame accuracy — whether that’s a timeline frame or a video frame — depends on quite a few factors. If your SWF was running at, say, 6fps,
_currentFramewouldn’t provide nearly the granularity as it would in a SWF set to 24fps, or 60fps. By the same token, FLVs can only seek to keyframes — video keyframes, which are completely different from timeline keyframes — so if you encode your video with a greater density of those, you’ll find greater granularity than you currently do with methods likeseekSeconds()(even if your SWF were set to 1fps!).You can, but then your movie clip would only be a single frame long, so many of those movie clip features would be moot. The approaches I describe in the article are members of the various classes described (
NetStream, et al). The movie clip methods you’re interested in are members of theMovieClipclass and only apply to instance of that class. As such, you could import video content into a very long timeline and create a “SWF video file,” which would ultimately be viewed as aMovieClipinstance, but I believe you’d lose some of the valuable progressive download benefits of loading an FLV at runtime.When Macromedia (Adobe) says “You can apply the following actions to imported video objects in movie clips,” they’re saying you can apply those actions to movie clips (including dynamically loaded SWF files), and it really doesn’t matter what those movie clips (or SWFs) contain, including video.
Flash always provides a number of approaches to solve any goal, so experiment and see what works best for you — but if this were up to me, I would encode my FLVs with a greater number of keyframes. I would use
MovieClipfeatures for SWFs with animation,Soundfeatures for audio, and some combination ofNetStream(and other video-related classes) features for FLVs.December 19th, 2006 at 7:56 pm
So say you have a video at 15 frames per second. If it’s an swf I can go to 2.66 seconds easily with my_movieclip.gotoandplay(40), because frame forty is 2.66 seconds. If it’s flv, I can make every single frame a keyframe, if I want (I realize it makes for a bigger file). But even if every frame is a key frame, it’s pretty much impossible to go to 2.66 seconds because the Netstream seek() method only seems to take full second arguments. Likewise it seems I can’t know exactly when I am at precisely 2.66 seconds (or 40 frames) because Netstream time seems to give only full second feedback.
I suppose for this level of control, maybe I could embed a “cue point” at every single frame when encoding my flv (i guess essentially giving it timecode)… but this seems insane and I’m not sure if it would work.
Am I missing something?
December 20th, 2006 at 1:17 pm
John D,
I definitely agree that a cue point at every single frame is a monstrous prospect.
How are you determining that
NetStream.seek()only accepts integers? (Not saying I doubt you, by the way — just curious how you’re arriving at that conclusion.) I ask, because theSound.start()method, for example, supports an optionalsecondsOffsetparameter. Not the same thing, of course, but similar in concept, and that parameter does accept floats — e.g. 2.66 seconds (aka 2660 milliseconds).Your example (
gotoAndPlay(40)) makes sense, but even that depends on mathematical rounding; after all, 2.66 * 15 is 39.9, rather than 40. So even with your approach, which is a perfectly reasonable use of the given features, you’re dealing with a certain level of inaccuracy. It just happens that it falls within your comfortable limits.I haven’t personally needed to seek to a granularity of 100ths of a second, so I’m afraid my input at this point is only hypothetical. I wish I could speak with more authority on the subject; you’ve certainly piqued my interest!
The best I can give you is to restate a note from the
NetStream.seek()entry of the ActionScript 2.0 Language Reference:January 3rd, 2007 at 5:46 pm
this permits mute of each unique flv’s audio:
….
this.stream = new NetStream(this.myNetConnection);
this.container.flv.attachVideo(this.stream);
this.stream.setBufferTime(15);
this.container.createEmptyMovieClip(’flv_audio’, this.container.getNextHighestDepth());
this.container.flv_audio.attachAudio(this.stream);
this.audio = new Sound(this.container.flv_audio);
// save volume setting for un-mute
this.volume = this.audio.getVolume();
….
this.mute = function() {
var ismuted = (this.audio.getVolume() == this.volume)? true : false;
this.audio.setVolume( ismuted ? 0 : this.volume );
this.container.controller.mute_mc.sound_art._visible = ismuted ? 0 : 1;
return ismuted;
};
….
January 27th, 2007 at 8:22 pm
Hello David,
I am so grateful to you. So helpful. I have a rather sheepish feeling about this question. I’ll ask anyway.
Question 1.)
How exactly do I appply the above mentioned “action-scritp method” to load vars to the contentPath of a component. Perhaps a bit of code? Thanks in advance.
Question 2.)
I used the scripts you wrote above to try to add controls to external flv’s, but it did not work. I could view the video alright, but there were no controllers addedto the .swf. Please advise.
Here is my code:
===============================
// Code from the other article
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”http://wqam.com/admins/big_game/video/CC3_082306_002_qthigh.flv”);
// New code … assumes a button symbol with
// the instance name shown
btnPausePlay.onRelease = function() {
ns.pause();
}
===================
Please advise.
Thanks again for your help with both matters.
January 27th, 2007 at 8:53 pm
Drew,
I think what you’re asking here is, “How can I update the
contentPathproperty of a Component from ActionScript?” If that’s it, simply reference the Component’s instance name, follow that with a dot, then the property.Assuming the instance name is
videoPlayer, as above, you would do this:But be aware, that approach assumes you’re using a Component — presumably the FLVPlayback Component — and this article is specifically geared toward controlling a video without a Component. In order to find out whether your particular Component supports a
contentPathproperty, consult the Components Language Reference to find its class. The FLVPlayback Component is defined by theFLVPlaybackclass, and the older Media Components are defined by theMediaclass.Aha. I probably should have been clearer in the original article. The sample code in your version — and in my original article — shows how to invoke a handful of
NetStreammethods that control a Video object by way of theVideo.attachVideo()method. The ActionScript shown doesn’t add visual buttons or any other controllers, but rather, shows how to “wire up” controllers you create yourself. ThatbtnPausePlayreference, for example, might refer to aButtoninstance (that is, a button symbol) or aMovieClipinstance (a movie clip symbol) with that instance name.Does that clear it up?
February 5th, 2007 at 10:41 am
Hi,
I am trying to make a flv movie player with frame accurate seek control. However, using my test movie it only seeks to the next 250th frame. I created this movie using mencoder from a set of png files. I have now discovered that NetStream.seek only seeks to the next closest keyframe, and that mencoder’s by default generates a keyframe at least every 250 frames (my test images are very similar so no keyframes are generated by scene changes). Mencoder has a keyint parameter, and with a keyframe every 5 frames seek is fairly accurate. However, the movie is much larger now (as expected) and I would like to have a seek accuracy of 1 frame. Do you know other ways to improve the seek accuracy without requiring additional keyframes in the encoding process?
A while back I had a brief look at the flv file format, and I thought that each frame (key or intermediaries) can be easily found (as long as it was read of course). So I would say that, at least in theory, the flash plugin could seek to the closest key frame and add necessary intermediaries to seek to any frame.
BTW I am using progressive download.
Thanks.
February 6th, 2007 at 8:55 am
Gijsbert,
I consider myself a fair hand at ActionScript, but not especially knowledgeable about video. As I understand it — and you already mentioned this — seeking is only possible to (video) keyframes … and more keyframes means a bigger file. All I can suggest is that you experiment with varying amounts of compression and datarate, consider using mono vs. stereo sound, or at least reduce the sample rate of the audio. Like many things in life, it’s about balance.
I honestly wish I could help you more on this issue.
February 24th, 2007 at 11:11 am
NEWBIE ALERT!!!
I’m importing a video file into Flash 8 as a streaming FLV file. All I want to add to it is a little button that says “skip intro” that when clicked, jumps to a particular spot in the video. I don’t need any other controls. I’ve created buttons, added behaviors, created cue points, tried the component manager, and nothing I do seems to do a thing.
The Flash Movie itself is a single frame movie. Do I need to just import the whole video as individual frames and do it the old fashioned way?
I’ve tried to read through the posts to find a soultiuon, but I couldn’t find one that specifically addressed this issue.
Thanks,
Brad
February 25th, 2007 at 8:09 pm
Brad,
By “importing,” I take it you mean “loading,” right? I don’t mean to split hairs, but in this case, the distinction is important. Importing is when you use the Flash IDE (the authoring environment) to bring an external file directly into Flash, in which case the imported file is included with the SWF itself. Loading means you’re bringing an external file into Flash at runtime; that is, after the SWF has been published.
The reason this distinction is important is because you can’t send a video to a certain spot of that spot hasn’t yet loaded — not unless you’re using a streaming server.
Are you using the FLVPlayback Component, by chance? I ask, because the way to skip around in a video is depends entirely on the mechanism you use to play the video. This article was written to specifically address controlling video without a Component, which means I’d direct your attention to the
NetStream.seek() method, but you mention a “component manager,” so I’m not sure.What do you mean by the “old fashioned way”?
March 22nd, 2007 at 6:40 pm
regarding this line:
videoPlayer.attachVideo(ns);
Is there also a way to unload (unattach?!?) the video in videoPlayer after you loaded it? Say with a button somehwere on the stage…
March 22nd, 2007 at 6:49 pm
I think I found it:
close_btn.onRelease = function(){
stream_ns.close();
};
that would be the button on the stage i mentioned. Is that right?
March 22nd, 2007 at 8:24 pm
Michael,
Badda-bing, badda-boom. You got it.
Just make sure to reference the
NetStreaminstance by its instance name. In your first post (6:40), that reference wasns; in your second post, it wasstream_ns.March 26th, 2007 at 5:00 am
Hi,
firstly its great you help people out with this blog! hope you can point me in the right direction…
I have created a video & slides presentation that streams an flv & runs anims based on action script cue points. I have been asked to create a progressive version as well.
My problem is the FMS streamed version had buttons that jumped to scenes in the swf & flv - as it was streamed the video was instantly accessible. On the progressive version I need to make these links active as the flv loads so the user can only jump to that section if it has loaded.
(I’m using a media component & 1 bit of video 5 mins long)
I really don’t know the best way to tackle this, I know I can test for bytes loaded but how can I translate this into a cue point or that a point in the video has not passed but has been loaded. I could really appreciate some help.
In short I have 5 buttons so need functionality along the lines of:
if point 02.50 has been loaded,
make this button visible/active
(and then on the button the usual on release goto cue point etc)
any ideas? - I’m not sure if I would be better loading the video in AS rather than media component - while I know action script I am by no means an accomplished coder so was hoping there was a simple fix.
March 27th, 2007 at 9:21 am
Mikey,
For progressive download, cue points really can be an issue, as you’ve seen. It’s not enough to check for a ratio of loaded bytes over total bytes, because FLV files can be encoded with a variable bitrate, which means certain parts of the file may load more quickly than others — 50% loaded may or may not mean that 2.5 minutes of a 5-minute video have loaded. On the other hand, you’ll at least know that all cue points are available when the whole video has loaded.
This is a good question, no doubt about it. Off the top of my head, I’m afraid I don’t have an answer, but I’ve added this to my “to do” list.
March 30th, 2007 at 3:01 pm
Hi David,
thanks for getting back - I’ve been on another project but if I find a solution I shall certainly post it - let me know if you have any success.
thanks.
April 12th, 2007 at 6:32 pm
Hi David,
So, I’m in the process of teaching myself Flash (fun) while building a website. Your code explanation is great as I have a site that allows users to navigate through a variety of sub-menus in order to access different videos that they want to watch. By assigning a variable VIDCHOICE when they make their selection, I am now able to use a single frame of the timeline for playback within each submenu - instead of a new frame for each FLVPlayback component. Which is great.
My question is about skinning. The example you show above - is it possible to use this approach and one of the pre-existing skins that comes with Flash Professional 8 or am I restricted to either building my own buttons or using the component buttons.
Thanks!
April 13th, 2007 at 8:02 am
Kevin,
The FLVPlayback skins are tailored to the FLVPlayback Component. You can use the FLVPlayback Custom UI buttons to mix and match, but they don’t give you nearly the variety (or convenience) of the pre-made skins. If you want to use the FLVPlayback Component, substitute your
VIDCHOICEvariable with thecontentPathproperty of your FLVPlayback instance. That way you’ll benefit from the robust UI of the Component and still be able to conserve timeline frames.April 13th, 2007 at 2:23 pm
David,
Thanks for the help - that answered my question! I like the simplicity of the solution here, so I think I’ll go that way.
One other question - this one’s about the volume bar. Using my newfound understanding of ActionScript, I managed to implement audio controls. What I can’t figure-out, however, is how the volume bar is supposed to work - and the Flash documentation is remarkably vague about it’s use. I think that I need to use getvolume() - but how? And, as importantly, then what?
Thanks again for this blog and your responsiveness. Not to be overly dramatic, but I’ve posted several requests for help on the Adobe Forums and have gotten no feedback!
kevin
April 13th, 2007 at 6:41 pm
Kevin,
Video volume is a bit weird in that video-related objects —
VideoPlayer,NetStream, and the like — don’t control their own volume. Here’s the scoop (though this would make a good blog entry, so I’ll add it to my list)…. [Note, this has since been added: “How to Adjust the Audio Portion of Flash Video.”]You’ll need to create a new
MovieClipinstance just to act as the “audio container” for your video. It can be a movie clip symbol with nothing in it or you can create it dynamically with theMovieClip.createEmptyMovieClip()method. In either case, the movie clip needs an instance name so you can “talk to it” with ActionScript. After you set up your video via theNetStreamapproach above, you’ll invokeMovieClip.attachAudio()on the new movie clip’s instance name and pass in yourNetStreaminstance as a parameter.Finally, you’ll instantiate a new
Soundobject and use the new movie clip as the parameter for the sound object. So now you have a kind of chain: a sound object associated with a movie clip, associated with a video stream, all in the house that Jack Built. UseSound.setVolume()as normal on thatSoundinstance and you’re good to go.See the
MovieClip.attachAudio()entry in the ActionScript 2.0 Language Reference to get started, but again, I’ll write up a tutorial on this topic pretty soon.April 23rd, 2007 at 10:13 am
David,
Hi, I am kind of new to actionscript and I am having problems. I have a video that I have set a cue point in flv and now I need to call on that cue point in my flash actionscript so that it will load a swf that will place text on top of the video into a empty container on the stage. How do I do this?
April 30th, 2007 at 10:37 am
Thanks for the post David, stepping away from the “consumer tools” of Flash components is scary but eventually liberating. Right now I’m still in the “scary” mode as I’ve only been working intensively in Flash for about six months, and only very recently have I really started to tear into the FLV Playback component and its attendant controllers. I’m still not comfortable giving up the built-in functionality, but have hit a recent issue that is forcing me to look outside the safe world of components.
Last week I encountered a maddening “bug” with the SeekBar and VolumeBar components that, under certain implementations, leaves onscreen “artifacts” of the triangular drag handles associated with those components on subsequent re-plays of the video. You can accrue a nice little herd of those items along the way. To date I have not found a legitimate solution to the issue and I don’t know how in-depth you plan to go with documenting how to control Flash video with actionscript… but it’s certainly a problem that would benefit by the exploration of someone who understands Actionscript better than me at this point in time.
May 1st, 2007 at 3:02 am
Drewprops,
Wow, sorry to hear about that! I haven’t seen the artefacting you describe, but if I did, it would sure annoy me! My Flash video entries seem to get the most response lately, so I’ll certainly consider going into greater depth on AS-controlled video. Thanks for stopping by, in any case!
May 1st, 2007 at 3:34 am
Michelle,
I’m not sure I follow your question.
Here’s what I see:
So far, so good. The
NetStreamclass features anonCuePointevent. According to the docs, it should be as simple as assigning a function to that event:If you’re loading a SWF, you have a few options. My recommendation is the
MovieClipLoaderclass. When you mention text on top of the video, I wonder if you’re aiming to put together some closed captioning? If so, why not instead just keep updating thetextproperty of aTextFieldinstance?On that last part, I’m afraid I lose you.
May 3rd, 2007 at 4:54 am
David, I was doing a search on flvs, and came across your blog. Looks great, I’ll be back for sure!
I see a number of posts about keyframes vs. seeking and also how to determine whether enough of the flv has downloaded to know if seeking to a future timecode is possible in a progressive download. You may already be aware of this - I recently discovered (although its not new - its been around for a while) that its possible with a freeware tool to ‘inject’ metadata into the flv which provides arrays of timecodes and byte addresses for the keyframes. Using this information from the metadata can help to solve some of the problems. The tool is called FLVMDI and can be easily found with a search (I can’t remember - it might be windows only, its a commandline tool but there’s a gui available for it).
When coupled with a custom player and some supporting server side script (there are examples of this online using PHP), this approach can enable foward seeking within progressive downloads, even when the seek-to portion of the flv hasn’t yet downloaded. Basically (the way I understand things!) the custom FLV player can request the download of the specific portions that it wants to seek to (because its knows the byte address to request from the file on the server which it obtains from the keyframes object in the metadata).
May 3rd, 2007 at 7:54 pm
GWD,
Hey, thanks for the informative comment! I hadn’t heard of this software, but it looks great. Here’s the link for FLV MetaData Injector (FLVMDI), folks. Thanks again for the info!
June 8th, 2007 at 2:24 pm
Hello,
I am developing a small app to playback flv files. However, i want to add a feature called Fit to screen, in the playback controls. My playback component is 640*480, if the flv is sized more than that (assuming 800 * 600), as i am using a scroll pane too, the flv playback control would display the scroll bars. Now, when the user clicks on ‘Fit To Screen’ button, the flv should resize to 640 * 480 (proportionately 4:3), the player remains the same size. BUT the real problem is degrades in quality like hell, doesn’t even remain readable… Is there anyway to reduce this quality loss when the flv is resized (and i m resizing to a lower size than its original)? Just like what happens in acrobat connect when you put on ‘Fit To Size’ in the Screen sharing window. Kindly reply as i am in a desperate need of the solution.
June 14th, 2007 at 8:56 pm
Regarding the previously mentioned VolumeBar Handle component being left on stage. I had this problem a few months ago and the “fix” I found was to wrap the VolumeBar inside a movieclip. Unfortunately, it’s back. I’m just reusing the same movieclip containing the VolumeBar that I’m using elsewhere on the same site with no problems, but now it’s nested inside another clip, and the problem is back. What the heck causes this? It’s gotta be more common than a Google Search lets on. Any help would be amazing.
June 18th, 2007 at 9:10 pm
To Parag Shah …
Image degradation is often one of those “more an art than a science” challenges. This is especially tricky considering that your image is actually a series of images — specifically an FLV. There are all sorts of factors to consider when encoding video, including framerate, bitrate, and compression … they all have an impact on video performance, regardless how the video is resized.
With this particular question, I’m afraid there isn’t a quick fix (that I’m aware of). If there was, I’d let you know!
To Kevin …
Looking back at your previous comments, I think you mean that a volume slider wrapped in a movie clip twice has stopped working. If that’s it, you’ll need to make sure you reference that slider according to the object path it belongs to. The slider will have to have an instance name (settable in the Property inspector), and both of the movie clips, in turn, will have to have instance names. The reference, then, would be
myClipA.myClipB.mySlider— where the “my” terms would be the actual instance names of your own choosing.June 18th, 2007 at 10:18 pm
Hi David,
I’ve made a home page for myself here:
http://stefansargent.com
It’s obviously a progressive download. It plays ten movies and then loops. A steal of Apple’s CoverFlow look but I did it in Final Cut Pro.
I’d like to make it interactive so that when (say) the Music Choice video is playing if the user clicks and it goes to the Music Choice page in my ARCHIVE section. I tried cue points - with zero success. I’ve come to the conclusion that it can’t de done - or can it?
TIA - Stefan
June 20th, 2007 at 8:28 pm
hey david,
first, your blog has helped me a lot so far in understanding how to play an external flv dynamically.
I have a question about controlling the play of the FLV without buttons. Is it possible to pause the FLV say 5 seconds into the video then play the rest of the video on the press of a button.
if that was too vague, let me clarify. what i’m trying to do is play the flv and stop it at a certain point. (im not sure if I should use a cue point here) then play the video when a button that will pop up appears. I’m also a little unclear how to use cue frames so I’m not sure the best way to structure this project.
I have been reading up on cue frames and I think I could use actionscript cue frames but i’m not sure about using actionscript cue frames on a dynamically loading FLV.
If I could get any help it would be much appreciated. If this is asking too much, sorry. but I cant seem to figure this out. thanks! keep up the good work!
-ryan
June 24th, 2007 at 11:49 pm
ryan,
Pausing an FLV file at five seconds could be accomplished with the
setInterval()orsetTimeout()functions as described in the “How to Pause a Timeline” post (withsetTimeout(), you don’t even need to clear the interval). At the five second (or whatever) mark, you would simply invokeNetStream.pause()on yourNetStreaminstance (that’snsabove).I could see using a cue point, just as well. In ActionScript 2.0, you’ll have to publish to Flash Player 8 or higher to use cue points with the
NetStreamclass. All you have to do, really, is assign a function to theNetStream.onCuePointevent, like this:… assuming you could rely on it that the cue point in question was the only one — or that it was the first one, the one supposed to pause the video. If not, you could use an incoming parameter (provided by the event) to test the content of the cue point:
The
NetStream.onCuePointentry of the ActionScript 2.0 Language Reference tells you what properties can be checked against, and those correspond to the data you can input while adding cue points by hand in Flash as you import video.June 27th, 2007 at 2:47 pm
Hi David,
Thank you for creating this blog. Without your answers and solutions on loading external FLV video, I would have never gotten as far as I have in my project.
I am building a flash website that will play a 5 minute video on Work Zone Safety. Once the cue has been hit on the video, it goes to frame 5 and plays a flash quiz that uses xml.
With your help and the help of your members, the video is loading, playing and cueing great. I even built my play and pause buttons as you instructed and they work. My question is, can I also include a progress bar, too? If so, do you have or know of a tutorial that will show me how to do this and work with my existing video?
Last question, since this is our first time building such a project, and considering that web traffic could be high, we are going to use streaming services like Vital Stream or Lime Light. Is there anything I need to do differently with my FLV and or action script code since we won’t be hosting it on our servers?
Thank you.
June 27th, 2007 at 10:13 pm
Rick,
You’re welcome, for sure! This is the sort of feedback that keeps me going.
A custom progress bar shouldn’t be difficult. I’m on an FLV kick at the moment, so I’ll try to have a progress bar example ready in the next week or so. The approach will be to use a loop to repeatedly check the
NetStream.timeproperty against the known length of the video. That ratio will allow you to move a circle (or some such) across the width of a rectangle, or adjust the size of some movie clip, thermometer style, as the video progresses.For the streaming question, you’ll drop the
nullin yourNetConnection.connect()call and replace that parameter with a path on the streaming server. Pretty much everything else is the same.June 27th, 2007 at 11:02 pm
[Replying to June 18, 2007 post.]
Stefan,
You should be able to achieve what you’re after, but I’m not sure I quite follow the gist yet.
June 28th, 2007 at 8:09 am
Thanks David. I’ll be anxious to see your tutorial. I mentioned your blog at Expert’s Exchange.
June 29th, 2007 at 1:14 pm
Hi,
I was just wondering if there was a way to detect that stream has ended (i.e. that you are at the end of the file)
My reason for asking is that once one FLV file has finished I want to play a second movie.
June 29th, 2007 at 1:42 pm
Kieran,
Check out “How to Determine the Completion of a Flash Video (FLV) File.”
July 9th, 2007 at 4:26 pm
Sorry to ask this question - since it involves the FLV Playback components!
I would like to control a movie clip (aka swf file) using the cute little buttons
found in the FLV PlayBack Custom UI. I am not controlling video.
Is there a way I can program/use these buttons to control a movie clip?
(like PlayButton, etc) I would like to be able to use the “over”, “down”, etc.
I see where the componenets have a script section and a content section (i mean “frame”).
It would even be nicer if I could just drag a movie clip (or use the loadMovie or attachMovie methods) on the FLV Playback guy, and work it from there.
What is the best way to do this? I am trying to avoid making new buttons, and applying the up,over,down,hit actions, etc.
thanks,
eholz1
July 10th, 2007 at 1:54 pm
eholz1,
You can indeed program the FLV Playback Custom UI buttons to control movie clips. Just treat them like movie clips themselves and handle whatever
MovieClipevents you want. The problem with these UI buttons is that they don’t respond visually (this is my hunch) as you would expect.Not sure what you mean here at all.
Sorry!
I’m not sure what you mean here, either — especially by “applying the up,over,down,hit actions.” Do you mean you prefer not to create button symbols from scratch? Are you not comfortable creating the visual aspect for each state, Up, Down, and Over?
You will have to “apply actions,” if by that you mean “use ActionScript,” to tell these buttons how to perform.
Have you looked under Window > Common Libraries > Buttons to see some of the pre-built buttons there? The ones under “playback rounded” (the grey ones) are in the ballpark of the UI buttons. These are actual button symbols that you can easily edit to suit your color preferences.
July 11th, 2007 at 3:43 pm
David,
Question, is there a way to have the video already set to the “pause” position when its being loaded? I do not want the video to start until the user presses the play button.
Thanks so much!
Great blog by the way.
July 12th, 2007 at 12:20 pm
Nick,
I ran into this myself not long ago. In theory, it should be as simple as calling
NetStream.pause()immediately afterNetStream.play():… but I found that, for me, that made the video pause a frame or two past the beginning, rather than the exact beginning. To remedy that, I hacked around it to seek to 0 after a tiny pause. It may not be the cleanest solution, but it worked for me:
July 18th, 2007 at 2:07 pm
Very nice blog; very good articles. I have been reading and using your examples to setup a dynamic file that will play videos passed to it through a URL string. Everything is working smoothly so far, except the play/pause functionality. I’ll post my code below, then explain…
movPlayPause.btnPause.onRelease = function() {
ns.pause(true);
movPlayPause.gotoAndStop(2);
}
movPlayPause.btnPlay.onRelease = function() {
ns.pause(false);
movPlayPause.gotoAndStop(1);
}
What I am trying to accompish is this: 1) User clicks the Pause button to pause the movie, 2) Pause button switches to a Play button, 3) User clicks the same button (now Play) to continue playing the movie. The problem is that once the movie is paused, I cannot get it to play again. Both buttons are contained within a movie called “movPlayPause” and btnPause is on frame 1 with btnPlay on frame 2, both held with Stop actions to prevent the movie from looping at startup. My logical brain says the code above should work, being that as soon as you release the Pause button, the Play button is displayed and is ready for the users next click, which would then start the movie up again and display the Pause button.
Any ideas on this would be much appreciated.
July 25th, 2007 at 12:25 pm
Ben,
You’re close! The problem with your current approach is this: when
movPlayPauseis on frame 1, the only of its movie clip children that is currently accessible isbtnPause. ThebtnPlayinstance is on frame 2, right? Therefore, youronReleaseevent handler doesn’t actually get assigned. WhenmovPlayPause’s playhead moves to frame 2,btnPlayis just sitting there without any associated programming. If both of these movie clips exist on both frames, that would do it. You might use ActionScript to toggle the visibility and enabled properties of the relevant “off” movie clip — in which case you wouldn’t even need 2 frames, to be honest. Another approach would be to combine your pause and play buttons into a single movie clip. UsegotoAndStop()as before, but do so in response to a Boolean variable. Here’s a rough sketch:July 26th, 2007 at 10:32 am
hi
great explainations david
i need a quick help
in above reply to ben u have written a script to toggle between 2 state movie clip on frame 1 and 2
what if i want to have it for 4 labels
like play ,pause, while play over and while pause over
kindlt guide me how to modify this script for 4 states
like i want to know if my movie is playing and when i rollover movie clip it chnges colour or do anything .. i hope u hacve got the idea of what i asked
thanx a lot mate …
July 30th, 2007 at 6:29 pm
nab,
Your best bet is to dig into the
Buttonand/orMovieClipclass entries of the ActionScript 2.0 Language Reference; those will tell you what the full complement of available event are. If you want to handle a specialized rollover, you might, for example do this:Add as many frames to the
movPlayPausemovie clip as you please. The “trick” here is simply to handle existing events (here,onRollOverand use those events to updatemovPlayPausevisually, do something else (such asns.pause()above), or both.July 30th, 2007 at 10:48 pm
well thanx a lot david
but can u explain in little detail cuz i think i didnt get it completely
thnx again
July 31st, 2007 at 8:54 pm
nab,
Actually, you’d just combine the above two examples (but maybe I don’t understand what you’re after?).
In the above code, clicking the button toggles it on or off. While the
toggledvariable istrue, the video is paused. My understanding is that you want two rollover states, one for when the video is paused (toggleistrue) and one for when it isn’t. To send the movie clip to these two additional new frames, you could put the relevant artwork on frames 3 and 4 (or wherever you like — or use frame labels) and use anifstatement, as shown, to decide between them.August 2nd, 2007 at 5:48 pm
ok let me put it in detail again
i have a playpause button as movie clip
in it i have 3 layers
1 action 2 labels 3 graphics which has 4 section from play to pause for each label
i wanna chk if the movie is playing then on rollover play icon to chnge while the video is playing and same thing goes for pause
u did get me right earlier so that was i was heading for
thanx a lot
August 6th, 2007 at 10:44 am
hi david kindly tell us that how to make videos playin in flash custom player sitch to full screen mode and on escape go back to original screen resolution
thnx
August 6th, 2007 at 3:37 pm
nab,
Gotcha. I’m assuming that various artwork exists on several frames of this movie clip.
Why only three graphics? I was thinking you would want four, and perhaps one label per graphic.
There isn’t specifically a property, such as the fictional
NetStream.isPlaying, that states whether or not the video is playing. The quickest way I can think of is to create a Boolean variable of your own, as shown, and check that instead. My above suggestion checks that Boolean (toggled) and invokesNetStream.pause()as appropriate in response, as well as sending the playhead to the relevant artwork by way of a given frame. In theMovieClip.onRollOverevent handler, it merely sends the playhead to the desired frame (could be a label), based on that same Boolean.As for the full screen question — truly full screen — only Flash Player 9.28 and higher is capable of switching to this mode. Here’s a terrific four-page tutorial article on the subject. Covers both AS2 and AS3! Good stuff.
August 7th, 2007 at 11:47 am
thnx david
ur a GOD send
August 13th, 2007 at 1:53 am
hello once again david
thanx
tell me some thing
how can we make the flv player read the content of the media folder into its list dynamically without using xml
i dont want to use xml to display data in play list but i want the player to automatically read the folders and display the media present in it which is .flv in its list so when we click on one it plays
August 13th, 2007 at 4:19 pm
hi David,
just wanted to thank you for the article and, most of all, for the answers to all the q’ found in all the posts.
regards,
goliatone
August 13th, 2007 at 7:25 pm
To nab …
Unfortunately, Flash Player is not capable of reading the contents of file folders, for security reasons. (One exception, which is a special case that doesn’t apply here, is the
FileReferenceclass, which lets the user browse on a local machine for a file to upload.) What people usually do in the scenario you describe is to write a server-side script (PHP, ASP, Cold Fusion, and the like) to scrape the folder contents and return the list when requested.To goliatone …
Thanks so much!
August 15th, 2007 at 2:59 am
thnx david

n thanx again for the another article on toggle buttons
have a nice day
August 15th, 2007 at 7:20 am
nab,
Sure thing.
[nab is referring to this article here.]
August 19th, 2007 at 9:31 am
hi david
i am again stuck in a problem
i have pic displayer and flv player in one page in my app
wat i wanna do is that when i select a person from the person list box the flv player and pic simultaneously populates the pics list and flv list in each of the players , so i can watch flvs and see pics of a particular person i select from my list of persons… any idea how to do it
August 28th, 2007 at 9:57 am
nab,
It will depend on what sort of list box you’re using, and what version of ActionScript. Assuming the v2 ListBox Component (ActionScript 2.0), you might handle, for example, the
ListBox.changeevent as follows:… where
lbNames(for “list box names,” but it could be whatever) is the instance name. Rather thantrace(), you would, of course, invoke something else. In the case of your video player, it might be:In the above snippet, the
evtvariable is arbitrarily named (as are practically all variables) and can be used to refer back to theListBoxinstance that dispatched thechangeevent, in this case by way of the expressiontarget.value.August 31st, 2007 at 9:31 pm
Just wanted to say that I found a lot of this information very helpful. Thanks, David!
September 1st, 2007 at 2:08 pm
Thanks David for adding interactivity to my homepage - my jaw droped!
You are brilliant! Great work!
http://stefansargent.com
September 1st, 2007 at 2:09 pm
so did my second “p”
September 1st, 2007 at 7:47 pm
To Mike …
You betcha. Thanks!
To Stefan …
Thanks for the kudos, man! I’m really glad to hear you enthusiasm at the results.
October 16th, 2007 at 3:41 pm
How do I maintain the correct aspectratio when loading video this way?
I will have several videos loaded into the same videcontainer but they will have different sizes…
Niklas
October 16th, 2007 at 4:31 pm
Niklas,
In AS2, the
Videoclass features both_widthandwidthproperties, as well as corresponding height-related properties. The ones without underscores are read-only and refer to the width and height of the video stream coming from theNetStreaminstance.You can read those values, then use that information to set
Video._widthand_heightto the same values (or percentages of the same). To maintain aspect ratio, just make sure you use the same percentage for each of your underscored values.October 24th, 2007 at 1:25 pm
i am trying to load multiple flv files on to one player and have the buttons call the movies. the issue that i am having is when i have more than one block of code for say two buttons it loads both movies but only plays the one at the bottom of the code list. do you have any suggestions on how to fix this. I am some what new to action script
October 27th, 2007 at 9:37 pm
gary,
I’d really have to see your ActionScript in order to visualize what’s going on in your file.
October 30th, 2007 at 9:38 am
i found a solution to what i was doing. i made different .swf files and then i made another .swf that calls these swfs with the flv file in it. thank you though
October 30th, 2007 at 2:03 pm
gary,
Sure thing.
Glad you found a solution!
November 1st, 2007 at 3:08 pm
Hi David,
I’m wondering if it’s possible (using your script for playing flv without a component) to play an flv, play it in reverse and continue this loop without any user controls. It’s for a screensaver so the file will be local. I’m just trying to cut the size in half by avoiding having to reverse the frames in a video editor.
I’ve searched for many hours & I’m thinking the answer is no, but would love confirmation from an expert.
thank you for sharing all of this great info.
Sara
November 1st, 2007 at 8:43 pm
Sara,
The trouble with playing video backwards is that. in a progressive download situation like this,
NetStream.seek()only seeks to video keyframes (as opposed to regular video frames). Most FLVs are encoded to place keyframes at specific intervals, such as a keyframe every 30 frames. Playing forward is smooth, but stepping backward seems to stutter because of the relative scarcity of keyframes.Even if you literally place a video keyframe in every frame, my hunch is that you’d still run into trouble, as even fast forwarding and rewinding by way of
NetStream.seek()tends to be a bit dicey. Since this is for a screensaver, and a large SWF isn’t such a worry, you might try importing the video directly into your FLA’s main timeline (or a movie clip) and running the Flash timeline backwards. A basic run-the-timeline-backwards routine goes like this:… which will start reversing from the timeline keyframe containing that script — but I should tell you that I’m writing this from out-of-town and don’t have any video samples to test against, so I’m not even sure that would work.
Without a doubt, your best bet is to use your video editor to render a copy in reverse order.
November 2nd, 2007 at 5:40 am
Hi. Im been reading here and i dont really get my head around this.
Here is the thing, i have a fla file that i have 10videos that i use progressive download on. It all works good. But the thing is that if i press my navigation to load a new page, it get’s stuck. I want load it before it´s done loading all the progressive download video. So that im looking for i a script that i can put on my navtigation that tell it to stop loading the video and move on to load the new page. How would i do it?
I tryed this on the button..But it didnt work.
on (release)
{
close_btn.onRelease = function(){
stream_ns.close();
};
_root.gotoAndStop(”pagetwo”);
}
Thanks…
November 2nd, 2007 at 11:15 am
Thank you for being so generous with your expertise!!!
Sara
November 3rd, 2007 at 10:47 am
To Daniel …
Based on your description so far, I’m not exactly sure why your movie is getting stuck. Closing the
NetStreaminstance might be a solution, but in any case, you’re right, the code you’re showing isn’t going to work.The thing is, you’re using two different approaches to assigning your button event handlers, and you only need one. If your
on()function is associated with thatclose_btninstance, then theon()code should look like this:… if directly attached, or …
… if on the timeline. But not both.
To Sara …
Thanks so much!
November 14th, 2007 at 7:13 pm
This is an awesome blog. I’ve built my player using all the advice listed here and it works great. Now I want to have buttons that when clicked will swap out the video currently being played. I tried this:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”Starcast_Flash_01.flv”);
this.createEmptyMovieClip(”videoAudioContainer”, this.getNextHighestDepth());
videoAudioContainer.attachAudio(ns);
var videoVolume:Sound = new Sound(videoAudioContainer);
videoVolume.setVolume(100);
ns.pause(true);
altMovieButton.onPress = function() {
ns.close();
}
altMovieButton.onRelease = function() {
ns.play(”solutions_employees.swf”);
}
and all it does is stop the video. None of the other controls work after that.
November 14th, 2007 at 8:14 pm
AVdes,
I’ve literally copy/pasted your code into a new AS2 FLA — with a Video object,
altMovieButton, and FLV names that exist on my own computer, of course — and it does work for me.I noticed you’re calling a SWF file, rather than an FLV, in your
onReleasehandler. Does it work if you change that SWF to an FLV?November 15th, 2007 at 1:21 pm
OMG I’m so stupid. your right. I thought I was missing something important. Thank you for catering to my nubeness.
You Rock
November 15th, 2007 at 1:26 pm
AVdes,
lol No worries! Have fun with it.
November 16th, 2007 at 1:44 pm
David
I am having a problem with Tab index for a button that i pulled from the library in flash. My supervisor wants to be able to tab to it and be able to press the ENTER key. I cant seem to get it to work, here is a sample of the code that is on the button. The error that I am getting is Attribute used outside class. Any help would be appreciated.
on(rollOver){
public tabEnabled= Boolean
Enter.tabEnabled = true;
Enter.tabIndex = 3;
}
on (release) {
varsToSend = new LoadVars();
varsToSend.uid = tUsername.text;
varsToSend.pwd = tPassword.text;
varsToSend.token = 1000;
varsToSend.send(”https://www.neocru.com/index.php”,”post”);
}
on (release, keyPress “”) {
varsToSend = new LoadVars();
varsToSend.uid = tUsername.text;
varsToSend.pwd = tPassword.text;
varsToSend.token = 1000;
varsToSend.send(”https://www.neocru.com/index.php”,”post”);
}
November 16th, 2007 at 5:14 pm
gary,
That error is probably happening because of the word “public” in your
rollOvercode. In ActionScript, “public” and “private” are keywords used to specify the scope of properties and methods in custom classes.You shouldn’t really need a
rollOverevent handler to respond to a keypress. By default, buttons and movie clips with mouse-related event handlers will already respond to the Tab key, so you shouldn’t need thetabEnabledpart either. For theon()approach you’re using here, something like the following should do it:That said,
on (keyPress)responds whether or not you’re actually on the object it’s attached to. Same goes for thekeyUpevent associated withonClipEvent(), so you may have to use anifstatement in your code to test for the button’s instance name (so you know which button it is) before performing actual instructions.November 19th, 2007 at 4:59 pm
your solution helped out a lot but i found that i had to add a button from the components to get the tab thing to work and use some code on the last frame of the movie. here is the code that was used after stop command.
enter_btn.onKeyDown = function () {
if(Key.isDown(Key.ENTER)){
varsToSend = new LoadVars();
varsToSend.uid = tUsername.text;
varsToSend.pwd = tPassword.text;
varsToSend.token = 1000;
varsToSend.send(”website goes here”,”post”);
}
}
still not to sure about actionscript.
November 20th, 2007 at 4:56 pm
gary,
You’re using the non-
on()approach now, which is almost certainly an improvement (see the “Museum Pieces” article for details). The v2 Components do have an API for tabbing, and it’s different from the built-in tabbing for objects that have mouse-related event handlers (you’ll see a yellow rectangle around those).Definitely glad you found a solution that worked for you!
December 12th, 2007 at 3:59 pm
Hi David,
Your blog is great! It’s really been helping me out big time with a project I’ve been working on. I have a question for you and I hope you can help out. I’m using the FLVplayback component along with the seekBar component in as3.
Do you know how i would go about setting the buttonMode to true on the handle?
Thanks!
December 13th, 2007 at 9:08 pm
Joe,
That’s a good question! In theory, you would only have to identify the instance name of the handle, and if it’s an object that supports the
buttonModeproperty, set that property totrue. In an ActionScript 2.0 document, the Debugger panel shows the hierarchy of movie clips and other objects … you just find the instance you’re after and boom, you know its name. In ActionScript 3.0 documents, that’s no longer the case. The whole debugging environment is different — better in some ways, but unfortunately lacking in others (such as the missing tree view of objects).I did read up on the SeekBar component, but the docs are still a bit foggy to me on the topic of AS3-based components. I’m confident there’s a way to accomplish what you’re after, but I’m afraid I don’t know it!
December 14th, 2007 at 1:35 pm
Hello David,
Just checking an idea. I’ve got two FLV’s (I’m getting sound from the second one) in two FLV playback components on two differnt layers. They both play great. Is there any way to control them in order not to loose sinc using the same PlayPause button? SeekBar? For example is it possible to assign something like this to the playpause button?
myVideo. playPauseButton = playpausebtn;
myAudio. playPauseButton = playpausebtn;
Thank you in advance.
December 15th, 2007 at 12:09 am
Anton,
Your idea is a good one, but unfortunately it doesn’t work like that. In the case of your code snippet, the PlayPauseButton button would only work for the second component it was associated with (i.e., myAudio). You could certainly control two FLVPlayback instances with a custom button, though. Just create a toggle button yourself, then use it to invoke
pause()orplay()on both instances.December 15th, 2007 at 6:47 am
Thanks David,
I hope that there is a way to control both FLVs with the same seekbar.
Actually, as far as I undersatnd, the most complicated problem in
my case to keep both FLVs in sinc. The toggle button somehow pause and play video and audio with shift.
Again, thank you for your help.
December 16th, 2007 at 9:22 pm
Anton,
Unless these FLVs were being streamed, I should think the sync problem would indeed be your biggest issue. It wouldn’t matter if the control widget was a seekbar, button, or anything else. Flash has to load and buffer each piece of content separately, but simultaneously — and with progressive download especially, those downloads will be in competition for bandwidth.
You might make a bit of headway if you set the buffer slightly higher than usual for both media and wait until each has its buffer full.
December 17th, 2007 at 10:47 am
How can I control the length of time a text file appears during a video without using the time line ba? I want to be able to enter the numerical data. I havent been to Flash school and am learning on the fly and could use some help.
Thanks
Timr
December 19th, 2007 at 4:38 pm
Tim,
You could probably use cue points for that, but there are a number of timing mechanisms in ActionScript, depending on what version you’re using. In AS2,
setInterval()andsetTimeout()let you repeat and delay functions of your own choosing, and in AS3, theTimerclass does the same in an even more powerful way.December 20th, 2007 at 11:31 am
This blog post has been a savior, to say the least. Below is the code I am using… it functions correctly. but the size of my video is incorrect. I’m puzzled at why its smaller then the video instance that is sitting on the stage…? I must be doing something wrong…
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play(”EP1-LOW.m4v”);
function asyncErrorHandler(event:AsyncErrorEvent):void
{
// ignore error
}
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
pauseBtn.addEventListener(MouseEvent.CLICK, pauseHandler);
playBtn.addEventListener(MouseEvent.CLICK, playHandler);
stopBtn.addEventListener(MouseEvent.CLICK, stopHandler);
togglePauseBtn.addEventListener(MouseEvent.CLICK, togglePauseHandler);
function pauseHandler(event:MouseEvent):void
{
ns.pause();
}
function playHandler(event:MouseEvent):void
{
ns.resume();
}
function stopHandler(event:MouseEvent):void
{
// Pause the stream and move the playhead back to
// the beginning of the stream.
ns.pause();
ns.seek(0);
}
function togglePauseHandler(event:MouseEvent):void
{
ns.togglePause();
}
December 31st, 2007 at 11:55 am
Scott,
What’s the aspect ratio of your Video instance? If your actual video file is 4:3 (standard NTSC) and the Video object is, say, 3:3, I believe the video image will contract to fit its container. Have you viewed the video file independently? It’s possible that the video itself was encoded with letterbox bars.
January 1st, 2008 at 10:12 pm
Hi - some helpful person posted this AS2 example on flashkit of setting a cuepoint as End so the main timeline would goto frame 3. I want to use it in AS3. Unfortunately I have not been able to get it going in CS3, no probs in f8. Any ideas how to upgrade… the script
http://board.flashkit.com/board/showthread.php?t=693411&highlight=cuepoint+end
error seems to point to 3rd line…. I’m going crazy feeling really frustrated please can somebody even alter the .fla and repost as AS3 Test !!!!!! happy 08
stop();
var flvListener:Object = new Object();
flvListener.cuePoint = function(eventObject:Object):Void {
if (eventObject.info.name == “End”) {
gotoAndPlay(3);
}
};
myFLV.addEventListener(”cuePoint”, flvListener);
January 3rd, 2008 at 9:55 am
HIPPY,
I was going to point you to the video cue points article on this blog, but it looks like you’ve already seen it.
Hope that works for you!
January 8th, 2008 at 11:14 pm
Hey Dave,
Love these blog articles very helpful.
I’m looking for control of an FLV in a bit of a different way though.
I have an external FLV embedded onto my timeline on frame 3. Once this FLV is finished playing I need it to jump to frame 3. Would I do this using Cue Points? Or another method. I’ve been googling for the past hour and haven’t been able to come across any solid advice.
Any ideas?
Thanks.
Mike
January 13th, 2008 at 2:13 pm
Mike,
I’m assuming this FLV has been imported into the timeline of a movie clip — is that right? If that’s it, the easiest way to go would be to add a keyframe script to the last frame of that movie clip:
this._parent.play();or maybe
this._parent.gotoAndPlay(3);… since you mentioned frame 3. Does that make sense? Let me know if I didn’t understand your question.
January 17th, 2008 at 10:07 pm
Dave,
I must say, after searching the net. your blog has been the most helpful. I simply dislike using components for FLVs. I understand how to compare the know video length for a progress bar as for how much video has been played. But I would like to have a progress bar for how much of the video is loaded, not how much is played. Im guessing there is no netstream.getBytesLoaded(); but is there a way to do this? I would like to have two progress bars, a playhead vs video loaded bar.
Thanks,
Rickey Ward
January 18th, 2008 at 12:04 am
Thanks, but I figured it all out. It really is that easy… I really appriciate your tutorial. It’s simplicity saved me on my current project.
you are AWESOME.
Kudos,
Rickey Ward
January 18th, 2008 at 9:00 am
Rickey,
Thanks for the encouraging words! Glad you figured it out.
January 28th, 2008 at 11:45 am
Dave,
I’m using the FLVplayback component to dynamically playback multiple FLVs in order… file1.flv to file2.flv to file3.flv and so on… I can see in my output that once file1.flv completes, it will automatically play file2.flv… I have buttons made that don’t interact correctly… If I click to play file5.flv, it should play file6.flv but it goes back to the last completed file.flv in the output box… Is there a way to set a variable to each button that says it should continue in order from the button clicked… Sorry, I’m new to actionscripting and can’t think of how to explain it much better.
Thanks,
Jordan
January 28th, 2008 at 5:43 pm
Need Help in keeping FLVPlayback components the same size after FULLSCREEN toggle is clicked. You can see example here http://asilance.com/web/PETE_03.html Will someone please help me! I don’t want the controls to become bigger as the FULLSCREEN mode is clicked!
Thanks in advance.
January 28th, 2008 at 6:31 pm
Your Blog certainly is great!
Could I please ask you the following:
I constructed a video player in the manner you outlined ( netstream object ), and its works fine in that swf.
However, if I then import that swf into another swf using loadmovie and loading the swf into a loader component, it no longer plays. I cant work out why not. Other action script functions, etc, work fine.
Thanks, Geoff Gartlan.
January 28th, 2008 at 8:30 pm
To Lance …
I think what you’re after is the
FLVPlayback.fullScreenTakeOverproperty. Set it tofalseand see if that does it for you.To Geoff …
Hrrrm, I can’t imagine any reason for what you’re seeing. I threw together a quick test case based on your description — at least, I think so — and it works fine. (To be honest, I’m not 100% sure what you meant by “using loadmovie and loading the swf into a loader component,” but I loaded my video SWF successfully into another by way of
loadMovie()and also by way of the Loader component. Did you mean a combination of those? Even that should work.)January 28th, 2008 at 10:32 pm
Thanks David.
If you say it works, then it must.
Yes, its a combination of those whereby a button is pressed and the swf is loaded in this way:
menu_mc.littleTakkers_btn.onPress = function () {
mcLoader.loadClip(”swf/littleTakkers.swf”,myLoader);
}
If you are sure that this works, and I think you are, then perhaps the path to the flv has changed once the swf is within the “top” swf? So it can’t find the movie. Is that possible.
Or I have mucked up a detail somewhere.
Thanks again.
Geoff
January 28th, 2008 at 11:46 pm
Geoff,
Man, I wish that was true! I would tell my challenging freelance projects that my code must work!
Ahh, that might be it! It all depends on where the parent-most SWF is, and possibly the HTML page in which it’s embedded. Check out these blog entries …
(Perhaps) Unexpected Point of View: SWF Defers to HTML
Unexpected “Gotcha” with Relative Paths in ActionScript
January 31st, 2008 at 10:06 am
Jordan,
Woops! Sorry I missed your question, a few replies back.
I don’t know what approach you’re using to play back your collection of FLVs. Maybe you’re running through an array? That’s my hunch. If so, and if you have a separate mechanism (these buttons) to playing videos on demand, you’ll have to program your buttons to do two things: a) play the desired video, which you’re already doing; and b) update whatever variable you’re using to story the currently playing video. In “How to Play Flash Video Files (FLV) Sequentially,” for example, your third button might do this:
Now, why would
button3setcurrentVideoto 2? The answer is because arrays start with zero, rather than one — so element 2 of thevideosarray is the third element. Of course, your own variable names might be different, and that’s fine. But that little snippet shows you one way to accomplish your goal (assuming you’re using an array to cycle through the videos).April 14th, 2008 at 5:24 am
Hi David
Cracking blog, I’m new to actionScripts and this has been amazing.
I have read and adapted the code to run my flv using on mouse over/out but cant work out how to get the movie to return to start after getting to the end after playing all the way through, any help would be great, code below - thx J:
// Code from the other article
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”MVI_1505.flv”);
ns.pause();
setTimeout(function ():Void {
ns.seek(0);
}, 10);
// New code … assumes a button symbol with
// the instance name shown
btnPausePlay.onRollOver = function() {
ns.pause(false);
}
btnPausePlay.onRollOut = function() {
ns.pause(true);
}
April 16th, 2008 at 4:28 am
Hi David
Found code just needed this at end:
ns.onStatus = function(info) {
if (info.code == “NetStream.Play.Stop”) {
ns.seek(0);
}
};
April 24th, 2008 at 3:22 pm
Jason,
Good job! Yes, that’s one of the ways to do it. I describe another approach elsewhere on this blog, but your approach is the more elegant.
May 18th, 2008 at 10:03 pm
Hello David
Im new to Flash and actionscript so bare with me, I have a flash site thats 600 x 800, I wish to load a new movie thats a swf that streams a flv, size is 450 x 300 but when ever it loads it plays at 600 x 800. I added –/ import mx.video.*;
my_FLVPlybk.maintainAspectRatio = false;
my_FLVPlybk.width = 450;
my_FLVPlybk.height = 300;
my_FLVPlybk.contentPath = “../video/loves_misfortune.flv”;
–/ into the sctionscript panel to maintain size,
I have a button to open said video with this this action–/
on(release) {
my_mc.onUnload = function () {
trace (”onUnload called”);
}
loadMovie(”../swf/movie player.swf”,_root);
}
–/
What I trying to get is, unload current player and load new movie with new size of 450 x 300
But as you can see Im not getting to work, I have other movies loading into player and they size just fine.
Do you think you can help.
Thank you
July 29th, 2008 at 10:48 am
David,
As many have mentioned, your blog is a great resource, thanks for sharing all of this info with us.
I have built a an FLV Player in ActionScript 3.0 using the VideoPlayer class. Do you have any experience with it? Do you believe it to be a better alternative than using the low level NetStream implementation?
In order to use the class inside of the Flash IDE without the FLVPlayback component I had to change the ActionScript 3.0 classpath. It’s obvious to me then that Adobe did not intend for us to use it in the way that I have. However, according to the documentation for the class, it seemed like the best choice to me.
The biggest reason I’m asking is because I’ve run into a bit of a brick wall when it comes to scrubbing through my videos. Updating the playhead position on every frame (Event.ENTER_FRAME) does not work very well. The best implementation I’ve found is to use a Timer object and update the playhead every half second.
Do you have an thoughts on the subject? Unfortunately there aren’t very many resources for this sort of project out there, so any insight will be appreciated.
Cheers.
September 4th, 2008 at 11:31 am
David-
First of all, thank you so much! You have bailed me out more than you know, just never posted. I’ll try to make this ’short and sweet’.
My problem is the same as Jason Hone had (4 posts up), I would like to restart the video as soon as it completes. I tried the code that he posted but couldn’t get it to work. I also tried your post on it and was also unsuccessful. Hopefully you can help me out again.
Here is the code:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
ns.play(”nuevo.flv”);
ns.onStatus = function(info) {
if (info.code == NetStream.Play.Stop) {
ns.seek(0);
}
};
btnPausePlay.onRelease = function() {
ns.pause();
}
September 4th, 2008 at 11:42 am
I wasn’t complete on what I meant about your solution to the replay. I got your code to work but it would only replay one time for a total of 2. I would like the ability to replay inifinitely.
var duration:Number = 0;
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
videoPlayer.attachVideo(ns);
if (replay != “true”) {
ns.play(”nuevo.flv”);
}else{
ns.pause;
}
ns.onMetaData = function(evt:Object):Void {
duration = evt.duration;
};
ns.onStatus = function(evt:Object):Void {
if (this.time > 0 && this.time >= duration) {
var replay = “true”;
ns.seek(0);
ns.pause();
delete this.onStatus;
}
}
btnPausePlay.onRelease = function() {
ns.pause();
}
September 4th, 2008 at 11:49 am
Nevermind! I got it. I used Jason’s solution:
ns.onStatus = function(info) {
if (info.code == NetStream.Play.Stop) {
ns.seek(0);
}
};
You have to make sure to put double quotes around NetStream.Play.Stop.
So, do this: if (info.code == “NetStream.Play.Stop”) {
Thanks though
You too Jason
October 16th, 2008 at 10:42 am
Hi David…
Thanks for the great tutorial…just one question:
Is there a way to loop the video?
Normally I would just apply this code to the component on the stage:
on (complete) {
this.autorewind =true;
this.play();
}
However, I cannot apply any code to the empty video player…
October 16th, 2008 at 3:47 pm
Nevermind…I was able to find the solution here: http://www.communitymx.com/content/article.cfm?cid=984BA
Basically just add this to the same frame of actionscript:
ns.onStatus = function(info) {
if (info.code == “NetStream.Play.Stop”) {
ns.seek(0);
}
};
Still, many thanks to David for the great tutorial which has saved me once again!
November 25th, 2008 at 7:23 pm
Hi David,
You’ve got such great info here. I found your site while trying to figure out a problem with the “go back to frame 1 after playing a FLV” via the netstream method. Do you have any idea why the last chunk of code below screws up my playhead positioning? There is a “play” button on frame 1, and all this code on frame 2:
//——–NETCONNECTION SETUP————–
var nc:NetConnection = new NetConnection();
nc.connect(null);
//——–NETSTREAM SETUP——————
var ns:NetStream = new NetStream(nc);
ns.onStatus = function(info) {
if(info.code == “NetStream.Play.Start”) {
progressBar.onEnterFrame = videoUpdate;
}
if(info.code == “NetStream.Play.Stop”) {
delete progressBar.onEnterFrame;
}
}
ns.onMetaData = function(info) {
ns.duration = info.duration;
}
//——–ATTACHING NETSTREAM————–
video.attachVideo(ns);
//——–PLAYING EXTERNAL FLV————-
ns.play(”Settle.flv”);
//————LOADBAR————-
loadbar.onEnterFrame = function() {
this._xscale = (ns.bytesLoaded/ns.bytesTotal)*100;
if(this._xscale == 100) {
delete this.onEnterFrame;
}
}
//————VIDEO UPDATE———–
function videoUpdate() {
progressBar._xscale = (ns.time/ns.duration)*100;
timecode.text = getTimecode(ns.time);
}
//————VIDEO SCRUBBER———-
loadbar.onPress = function() {
progressBar.onEnterFrame = videoScrub;
}
loadbar.onRelease = loadbar.onReleaseOutside = function() {
progressBar.onEnterFrame = videoUpdate;
}
function videoScrub() {
var dist:Number = (_root._xmouse-loadbar._x)/loadbar._width;
ns.seek(Math.floor(ns.duration*dist));
progressBar._xscale = (ns.time/ns.duration)*100;
timecode.text = getTimecode(ns.time);
}
playHead.onEnterFrame = function() {
this._x = Math.floor(progressBar._width + loadbar._x);
}
//————–This code works but breaks the playhead location———
ns.onStatus = function(info:Object) {
if (info.code == “NetStream.Play.Stop”) {
gotoAndPlay(1);
}
}
stop();
Any insight is greatly appreciated.
Best,
casimara
January 27th, 2009 at 10:32 pm
David:
I have Actionscript 2 code within a SWF that runs an external FLV file in the same folder as the SWF calling it. The puzzling problem is the Actionscript calls and runs the FLV perfectly on one of our servers, but there’s no video on our ColdFusion development server which is the first step in a three stepped server sequence (development-integration-production) to production. We want the Flash video to run on the ColdFusion servers. Where I work, server administration is out of my realm/control, but I’m hearing the issue may be at the server end with mime settings. Why not just use the server that runs the external FLV? We eventually want to locate all FLV files externally and to make things even more complex, link to them on another domain. I know, “that’s hard way to do things” but that’s what’s being strongly suggested. So if my code runs the external FLV on one server, but not the other, it seems a server adminstrator’s mime settings might need tweaking. Any further thoughts or suggestions? JJ
August 3rd, 2009 at 9:49 pm
Hi David
Sorry this another FLVPlayback component question, but not sure where else to put it. I’m a relative newbie.
I’d prefer to use FLVPlayback for ease of use and stability based on what I’ve read here on your fantastic blog; however I only seam to be able to find netstream code for the status of the video.
What I want to do is: know when the viewer has clicked pause (with the built-in FLV Playback skin controls), so that I can stop a movie clip (instance name: stills) which is also playing. And then play stills movieclip again on play of flv;
plus, for extra complication: have another movie clip invisible until the completion of flv, like so:
lastVideoFrame._visible = false;
var listener:Object = new Object();
listener.complete = function(evt:Object):Void {
lastVideoFrame._visible = true;
stills.stop();
}
videoPlayer.addEventListener(”complete”, listener);
but if the viewer then clicks play again on flv once it’s completed, I need to have
lastVideoFrame._visible = false;
stills.play();
Can I have a listener.play function? If so, does this have to be a separate listener, such as
var PlayListener:Object
Am I completely on the wrong track? Should I be using NetStream instead for complete control? Your infinite wisdom and simple way of explaining things would be much appreciated for this ActionScript struggler
August 18th, 2009 at 12:56 pm
Hey David,
Thanks for the insightful tutorials here, defiantely a help. Read through your posts here and havent come across this question. I am also a AS3 newbie and have two challenges that I am attempting to overcome.
Have a fully functional SWF with external FLV. The swf includes scrolling text that plays simultaneously with the flv video content. The issue, is that as the videos get longer, the more chance there is for mismatches between the scrolling swf text and the flv video content.
I am now attempting to:
- preload both the SWF and FLV together.
- insert player controls that control both the swf and flv simultaneously.
I have been chomping at this for a few days now, and cant seem to get it just right. Any assistance on this would be greatly appreciated. Also, Crackin Blog ~ Great resources and advice
August 20th, 2009 at 4:31 pm
Hi David
I am trying to create a map type game in which you drag an mc and when it hits an invisible flv, the flv starts playing. How do I do that? Can I make an flv invisible, and then visible when the mouse/mc rolls over it?
Please help.
Thanks
August 21st, 2009 at 9:12 am
To Davader …
Your code looks basically okay, honestly. In a case like this, where it takes numerous steps to achieve your goal (unload one clip, load another; the new clip loads a video …) it’s generally best to test each step along the way. That way, you can verify that each step is happening as expected. If you do nothing else but unload your first clip, does your
onUnloadhandler properly execute? If you load your new clip — just a SWF (one that doesn’t do anything) — does it properly load at the right dimensions?It sounds to me like your SWF (the second one) might be getting resized somewhere, which in turn resizes its movie.
To Adam …
Adam, your questions are all good and thoughtfully worded. Unfortunately, I haven’t toyed much with the AS3
VideoPlayerclass — even in the year since you originally posted your questions — so I’m afraid I don’t have any insight for you. Sorry!To Cesar …
[then later]
w00t! Glad you nailed that, Cesar.
I’m so behind in these replies, it’s a relief to me when I see that a reader managed to navigate through a challenge alone. (Makes me feel less guilty for taking so long to reply.)
To Steve C …
Cool deal! I have vague memories about that particular CMX article (by Tom Green). It’s possible Tom consulted with me on that one before posting it. If so, that would be funny. Glad you found an answer!
To casimara …
Your last chunk of code looks like this:
But I’m wondering if you should actually be using
gotoAndStop(1)(stop, as opposed to play)?To Jim J …
Gosh, that’s a good question! To be honest, Jim, I’ve been lucky enough not to have to worry about MIME settings at all. I’m afraid I’m dry on this one.
To Kristi …
Kristi, you’re not on the wrong track at all.
The listener mechanism is no different from how you outlined, and you can re-use that same
listenerobject (theObjectinstance named “listener”) for all your various events. Check it out:Does that help? (Note, the above code is AS2. Not sure which version you need.)
To Land Onlong …
Given the independance of video timelines from animation timelines, I’m not surprised to hear about the lack of synch, especially down the line. In a case like this, I would probably try to rely on the actual progress of the video as a reference for tweening the text programmatically. In AS3, use the
NetStream.onMetaDataevent to derive the duration of the video (assuming it has metadata, which it probably does). Once you now how long the video is, you can use anEvent.ENTER_FRAMEevent to trackNetStream.timerepeatedly to determine how far along the video has played. If the video is 10 seconds, for example, and the video has played 5 seconds so far, you know it’s halfway done (5 / 10 = 0.5). With that ratio, you’ll know how far to set theMovieClip.xoryproperty of your scrolling text.At zero seconds it, for example, the text shouldn’t be scrolled at all. Assuming its default resting position is 0 and the text has a width of 500, that could be set up something like this:
scrollingText.x = -(ns.time / duration * scrollingText.width);assuming …
scrollingText.x = -(0 / 10 * 500)(it sits there at 0)Using the same formula, the text would be scrolled 250 pixels to the left (that is, scrolled halfway to the left) when
ns.timeis 5 seconds …scrollingText.x = -(5 / 10 * 500)(now at -250)Bear in mind, of course, that I’m showing a simplified principle. You’ll have to check if
NetStream.timereturns its value in seconds or milliseconds, and you’ll have to check the value ofdurationfor the same. Be prepared to multiply or divide either value by 1,000 to potentially compensate, as the case might be. But that’s one basic approach, in a nutshell.To Barbara Confino …
You sure can. The way you do it depends on how you’re playing the video itself (FLVPlayback or
NetStream), but in either case, you can make it easy on yourself and wrap your chosen playback mechanism in a movie clip. In other words, convert your FLVPlayback instance to a movie clip symbol, or convert your Video symbol to a movie clip symbol. That way, you have easy access to theMovieClipproperties, methods, and events.Make sure to give your movie clip an instance name, because you’ll need that instance name to “talk” to your movie clip with ActionScript — and also to talk “through” it to the playback mechanism inside it (FLVPlayback or Video symbol). Once you have your movie clip in place — this container that holds your video — you can use, say, the
MovieClip.onRolloverandonRollOutevents as your triggers to set theMovieClip._visibleproperty of that clip. If you’re dragging, check out theMovieClip.onDragOverandonDragOutevents.What version of ActionScript are you using? I’ve been assuming AS2 in my reply so far, but if you let me know for sure, I can flesh out a better code sample for you.
October 28th, 2009 at 7:38 am
Hi David
Thanks so much for this tutorial! Has solved many problems!
I have some questions though:
I have 5 buttons but i only want the video to play on the ‘home’ button.
When i click on the other buttons i have added :
videoPlayer._alpha = 0
ns.close()
that hides the video and stops it, however when i click the ‘home’ the video is paused where i stopped it and the pause/play button doesn’t work (i want it to automatically start again).
What code should i add to my other buttons to- stop/hide/put video back to the start?
And what code do i use so that when the home button is pressed the video is at the start and plays automatically?
Many many thanks!
May 26th, 2010 at 8:09 pm
I get a choice of “stop script” or let script “continue”. I always choose “continue” and this resolves things in about 20 secs. But the messages are beginning to bug me. Help !