Build a Dynamic Video Player with ActionScript 3: Part 1 of 3

Almost every Flash developer has had to make a video player at some point. There are quite a few different ways of doing this; some people use the built in NetStream Class and some use the FLVPlayback component in Flash. Either way will work, but we are going to use the NetStream Class because of how much lighter it is and what you can do with it.

This is a large tutorial that will be broken down to three parts. Each part will build off the previous one until we have our final result. Our player will be able to use an XML file to populate three galleries with an unlimited amount of categories, and an unlimited amount of videos in each category.

Let's take a quick look at what we will be building in each part of this series:

Part 1

File setup, organize files and folders.

Understanding how the start file is set up.

Position items on the stage for startup stage resize.

Global rollover and rollout functions.

Set up our Net Stream class.

Get the video playing.

Add preloader functionality.

Set up controls for video playback. These include a play button, pause button, stop button, video timeline scrubber, and volume scrubber.

Step 1: Understanding the Source Files

The fist thing to do is to download the source files I provided. This is very important as I am not going to go over what things are named and how I set up the file. I will however give brief overviews of specific things I did (like how I made my buttons and other things that are important). Basically, I put all the objects on the stage, organized the library, created movieclips for everything, properly named all the movieclips on the stage and created button rollovers for all necessary buttons. Along with creating and exporting the necessary movieclips.

The next thing to note is how I set up my folders for this project. You should create a folder on your desktop named whatever you want (eg.my_AS3_Video_Player). Open this folder, drop the the "flv" folder you downloaded, along with the "playlist.xml" and "theater.fla" files. The "theater.fla" file is your start file. The "playlist.xml" file is the xml file that is pre written. Inside the "flv" folder you will see all the videos we will be using, along with a "thumbs" folder which contains 3 other folders. These three folders each have a thumbnail image of all the videos at different sizes.

NOTE: If you do not want to use the videos I provided you can use your own, but make sure they have an audio track in them or else you will not be able to tell if the audio scrubber is working correctly.

Your start file should already be linked to the output folder when you open up the "theater.fla" file. If you know how this works then ignore the next sentence. If you do not know how this works click on file > publish setting. You should be on the formats tab. Here you enter "../output/theater.swf" for your .swf and if you want to publish the .html you enter "../output/theater.html". You also need to go to the html tab and select percent for the dimensions. Otherwise your file will not center on the stage correctly.

The third thing you need to do is download the Caurina Tweener Class. Once this is downloaded you need to open the zip file and copy the caurina folder in your "src" folder so we can use it for our animations.

Step 2: Taking Note of Your Stage and Items

Now that you are set up with everything in place it's time to look through the file. The first thing to take note of here is your stage size 850x580, this is not really that important as it will be set depending on your window size. It is however the minimum size your window will go before cropping part of the player. Second is the 4 layers on the stage. The top layer is where we will be writing our code. The second layer is where we will have video controls, and the video. The third layer is where we will have the playlist with different galleries, categories, and videos. The fourth layer is where we will place the featured videos that are set with a simple true or false in the xml.

The other thing I would like to point out is the items we will be adding to this file based on our xml. We will be populating them at runtime from our library. There are 3 items that are named featuredItem_mc, videoItem_mc, and categoryItem_mc. They are found in the folders in the library and are already set to be exported when you publish.

Other than that, the buttons along with rollovers and dynamic text are already set up for you. Feel free to customize if you want, but we will go over those steps later.

Step 3: Let's Start Writing Some Code!

Let's import the necessary classes we will use for our tweens. We will also set our stage to align to the top left and set it to not scale. In the main timeline click on the AS3 layer and type the following:

Step 4: Name Objects on Stage

Now let's add some naming variables so we don't have to type such long instance names.

var videoBox:MovieClip = player_mc; // this will target the player mc on the main stage
var sidebarBox:MovieClip = rightSidebar_mc; // target the right sidebar mc on the main stage
var featuredBox:MovieClip = featuredBox_mc; // target the featured box mc on the main stage
var featuredBoxBg:MovieClip = featuredBox_mc.featuredBoxBg_mc; // target the featured box's background in the featured box

Now if you test your movie your content will be centered in the middle of your .swf file. But not if you resize your .swf. So let's take care of that.

Step 6: Add Stage Resize Listener and Function

Next we need to take care of what happens when you change your .swf width and height or your browser size. To do this type the following code below the setMyStage function:

NOTE: I usually put all my listeners together near the top of the code and all my functions together in the bottom. Some people do this in reverse. There is no perfomance benefit, but it does help to keep your file more organized. From here on whenever I add a listener I will be putting it below the last listener at the top and when I add a function I will be placing it below the last function on the bottom of the page. Oh, and you should also always place your variables at the top one after another.

Step 8: Button Rollover and Rollouts

Here we will be using the same function for all of our rollovers and rollouts. The reason for this is that it reduces code, plus all the buttons we'll be using will be doing the same thing, so why not just make one function that is reusable?

Step 9: Global Functions for Buttons

Let's add the two functions that allow us to add rollover and rollouts to any button which is set up as described in the next step.

function btnOver(event:MouseEvent):void
{
event.currentTarget.gotoAndPlay("over"); // Targets the current movieclip when the mouse rolls over it and tells it to go to the over label keyframe and play
}
function btnOut(event:MouseEvent):void // Targets the current Movieclip when the mouse rolls over it and tells it to go to the out label keyframe and play
{
event.currentTarget.gotoAndPlay("out");
}

Now if you test your movie the buttons will change when you roll over and go back to their original state when you roll out.

Step 10: Rollover and Rollout Functionality

Let's take a second to see how I create my buttons and how all the buttons and movieclips in this tutorial are set up. You don't need to perform this step, but if you want to follow along go to the playBtn_mc movieclip in the player_mc movieclip and open it.

The first thing to do is design your button. Next, convert it to a movieclip and give it an instance name. If it's a play button I would name it something like "playBtn_mc". Give it the correct instance name. Lock these layers so you don't accidentally place symbols on them. Once you do that open up the movieclip and create two layers on top of everything. Name one layer "AS3" and the second layer "Labels".

On the first frame of the AS3 layer open your ActionScript panel and type "stop();". Do the same on the 10th frame. On the second frame of the Labels layer create a keyframe and highlight it. Now go to your properties panel and in the Name field type "over". Now go to the 11th frame on the Labels layer and create another keyframe. Select each element separately and convert to a MovieClip. Once completed, select all and separate to layers. You can use the right-click (context) menu, or setup a keyboard shortcut. Since I'm constantly separating elements to layers I find it helpful to create a "Ctrl + D" shortcut [Command + D] on a Mac. (Note: the name of the layer will be based on the name you gave each symbol.)

Don't worry about giving them instance names, since we will just be tweening them. If you don't convert each element you want to animate to a symbol, then Flash will create tweens in your library that become messy. Go to the 10th frame of the layer you want to tween and create a keyframe, then go to the 20th frame of the same layer and create another keyframe.

Now highlight all the layers frames and right-click. Select "create classic tween". Don't deselect just yet, go to the properties panel. Select the tween tab and enter 100. Now select the 10th frame of the layer and go to the properties panel and select the style tab. Here you can select what you want the current element to do. That's it. You can also change how long the animation takes on rollover and rollout by moving where the stop actions are and the over/out label keyframes are.

This is how all the buttons are set up in this tutorial, so anytime you see a rollover or rollout this is how I did it. With the code from steps 7 & 8 and the button from this step you can create a button with rollover and rollout functionality in any project.

Step 11: Make Movieclips Behave Like Buttons

Let's add buttonMode and mouseChildren to our buttons. Add this below your variables at the top of your code.

Step 13: Setting Up Our NetStream Object

Here we will set up a variable that collects the current video from the xml and sets it to a string. We'll also set the video height and width with a Number that will eventually change when we open a new movie. Add the following variables to the list of variables at the top of your code:

var currentVideo:String; // this string will be used to play the current video selected
var videoWidth:Number = 500; // this will set the width of the video object and can be changed later on
var videoHeight:Number = 400; // this will set the height of the video object and can be changed later on
var duration:Number; // we will use this later to get the duration of the video being played

Step 14: Create a Video Object

Now that we have all the functionality set up for the player, it's finally time to get a video to start playing. We first need to create a video item, set its position and add it to the stage in the correct layer. Below everything in your ActionScript layer type the following:

var video:Video = new Video(videoWidth, videoHeight); // create a new Video item and set its width and height
video.x = 0; // position the video's x position
video.y = 0; // position the video's y position
videoBlackBox.addChild(video); // add the video item to the videoBlackBox movieclip in the player_mc movieclip

Step 15: NetConnection and NetStream Connection

Now we need to create a new NetConnection and link it to the new NetStream connection along with some listeners for the NetStream. Add this to your code:

var video:Video = new Video(videoWidth, videoHeight); // create a new Video item and set its width and height
video.x = 0; // position the video's x position
video.y = 0; // position the video's y position
videoBlackBox.addChild(video); // add the video item to the videoBlackBox movieclip in the player_mc movieclip
var nc:NetConnection = new NetConnection(); // variable for a new NetConnection
nc.connect(null); // set the nc variable to null
var ns:NetStream = new NetStream(nc); // create a variable for a new NetStream connection & connect it to the nc variable
ns.addEventListener(NetStatusEvent.NET_STATUS, myStatusHandler); // add a listener to the NetStream to listen for any changes that happen with the NetStream
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); // add a listener to the NetStream for any errors that may happen
video.attachNetStream(ns); // attach the NetStream variable to the video object
var newMeta:Object = new Object(); // create a new object to handle the metaData
newMeta.onMetaData = onMetaData; // when we recieve MetaData, attach it to the newMeta object
ns.client = newMeta; // attach the NetStream.client to the newMeta variable
ns.bufferTime = 5; // set the buffer time to 5 seconds

Step 16: NetStream Functions and Buffer Video

Now let's add the functions to handle what happens when there is a specific video event or an error with the connection. We will also handle the buffer for the video. Add the code below:

function asyncErrorHandler(Event:AsyncErrorEvent):void
{
//trace(event.text); // this will handle any errors with video playback
}
function myStatusHandler(event:NetStatusEvent):void
{
//trace(event.info.code); // this will handle any events that are fired when the video is playing back
switch(event.info.code) // switch statement to handle the various events with the NetConnection
{
case "NetStream.Buffer.Full": // when our buffer is full fire the code below
ns.bufferTime = 10; // set buffer time to 10 seconds
Tweener.addTween(videoPreloader, {alpha:0, time:.3}); // tween videoPreloaders alpha to 0
break;
case "NetStream.Buffer.Empty": // when our buffer is empty fire the code below
ns.bufferTime = 10; // set buffer time to 10 seconds
Tweener.addTween(videoPreloader, {alpha:1, time:.3}); // tween videoPreloaders alpha to 1
break;
case "NetStream.Play.Start": // when our video starts playing we fire the code below
ns.bufferTime = 10; // set the buffer time to 10 seconds
Tweener.addTween(videoPreloader, {alpha:1, time:.3}); // tween videoPreloaders alpha to 1
break;
case "NetStream.Seek.Notify": // when you seek with the scrubber it sends a notify signal of the time
ns.bufferTime = 10; // set the buffer time to 10 seconds
Tweener.addTween(videoPreloader, {alpha:1, time:.3}); // tween videoPreloaders alpha to 1
break;
case "NetStream.Seek.InvalidTime": // when you release the scrubber ahead of the video that has been loaded, you get this error. it will jump you back to the last frame that has been loaded
ns.bufferTime = 10; // set the buffer time to 10 seconds
Tweener.addTween(videoPreloader, {alpha:1, time:.3}); // tween videoPreloaders alpha to 1
break;
case "NetStream.Play.Stop": // when you reach the end of the video
Tweener.addTween(videoPreloader, {alpha:0, time:.3}); // tween videoPreloaders alpha to 0
ns.pause(); // pause the video
ns.seek(1); // seek the video to the first frame
break;
}
}
function onMetaData(newMeta:Object):void
{
//trace("Metadata: duration=" + newMeta.duration + " width=" + newMeta.width + " height=" + newMeta.height + " framerate=" + newMeta.framerate); // traces what it says
duration = newMeta.duration; // set the duration variable to the newMeta's duration
}

Step 17: Play the Video!

Finally, add this line of code to play the video:

ns.play("flv/bsu-football-open.flv"); // tell the netstream what video to play and play it

Now if you test your video it should play. It will be scaled weird because we have not used the xml file to set the width and height. Don't worry about this yet, we will handle that problem later. None of the buttons will work and the scrubber bar will not be working. That's because we haven't linked them yet, so let's do that now.

Step 18: Add Listeners for Buttons

Now let's add some listeners for our buttons so we can get some functionality working.

playBtn.addEventListener(MouseEvent.CLICK, playBtnClick); // add a click listener to the playBtn
pauseBtn.addEventListener(MouseEvent.CLICK, pauseBtnClick); // add a click listener to the pauseBtn
stopBtn.addEventListener(MouseEvent.CLICK, stopBtnClick); // add a click listener to the stopBtn

Now if you test your movie and click the pause button, your video should pause. If you click the stop button your video should jump to the first frame and pause. If the video is paused or stopped you can click the play button to resume the video. Now let's get the timeline and volume scrubbers to work.

Step 20: Add Volume Scrubber Variables and Listeners

We need to add some variables to our code so we can get our volume scrubber working.

var videoSound:SoundTransform; // variable to control the global sound in your movie
var volumeBounds:Rectangle; // variable to set the volume scrubber bounds
volumeThumb.addEventListener(MouseEvent.MOUSE_DOWN, volumeScrubberDown); add a MOUSE_DOWN listener to the volume scrubber thumb

Step 21: Add Volume Scrubber Code

Let's add all the code to get the scrubber to work.

videoSound = new SoundTransform(); // creates a new SoundTransform object
videoSound.volume = 1; // sets the SoundTransform object to 1 which is 100%
ns.soundTransform = videoSound; // links the video to the SoundTranform object
function volumeScrubberDown(event:MouseEvent):void
{
volumeBounds = new Rectangle(0,0,75,0); // sets the bounds for the scrubber
volumeThumb.startDrag(false, volumeBounds); // when you click and drag the volumeThumb movieclip it runs this function
stage.addEventListener(MouseEvent.MOUSE_UP, volumeThumbUp); // add listener to the stage for when your mouse releases the click
stage.addEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove); // add listener to the stage for when your mouse moves
}
function volumeThumbUp(event:MouseEvent):void
{
volumeThumb.stopDrag(); // stops the volumeThumb from being dragged
stage.removeEventListener(MouseEvent.MOUSE_UP, volumeThumbUp); // remove this listener from the stage
stage.removeEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove); // remove this listener from the stage
}
function volumeThumbMove(event:MouseEvent):void
{
volumeTrack.width = volumeThumb.x; // sets the blue bar in the volumeScrubber to the width of where the scrubber is
videoSound.volume = (volumeThumb.x) / 50; // sets the volume of the video to a percentage of the track depending on where your volumeThumb.x location is
ns.soundTransform = videoSound; // actually transform the volume.
}

Test your movie now. You can scrub the volume thumb and hear the audio change!

Step 22: Scrubber Variables and Listeners

We need to add some more variables for the video timeline scrubber. Type the following in the vars section of your code:

var videoInterval = setInterval(videoStatus, 100); // duration between intervals, in milliseconds
var amountLoaded:Number; // variable to tell us how much of the video has been loaded
var scrubInterval; // variable for the timeline scrubber
videoThumb.addEventListener(MouseEvent.MOUSE_DOWN, videoScrubberDown);

Step 23: Add Functions for the Video Scrubber

Let's add the functions that will allow us to scrub the timeline and also move the scrubber bars to track amount played and amount loaded.

function videoStatus():void
{
amountLoaded = ns.bytesLoaded / ns.bytesTotal; // set our amountLoaded variable to a number that is the bytesLoaded divided by the bytesTotal of the video
videoTrackDownload.width = amountLoaded * 340; // sets the width of the videoTrackDownload bar to the amountLoaded var and multiply it by the track width.
videoThumb.x = ns.time / duration * 340; // move the videoThumb x position to the location on the track that is linked to the current video timeline
videoTrackProgress.width = videoThumb.x; // changes the width of the videoTrackProgress bar to the x location of the videoThumb
}
function videoScrubberDown(event:MouseEvent):void
{
var bounds:Rectangle = new Rectangle(0,0,340,0); // sets the bounds for the video scrubber based on the width of the scrubber
clearInterval(videoInterval); // clear our videoInterval so we can scrub
scrubInterval = setInterval(scrubTimeline, 10); // sets the scrubTimeline listener to update the video
videoThumb.startDrag(false, bounds); // starts to drag the videoThumb within the bounds we set
stage.addEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo); // add listener to the stage to listen for when we release the mouse
}
function scrubTimeline():void
{
ns.seek(Math.floor((videoThumb.x / 340) * duration)); // seeks the video to the frame related to the videoThumb's x location on the scrubber track
}
function stopScrubbingVideo(Event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo); // removes this listener when we release the mouse
clearInterval(scrubInterval); // clears the scrubInterval listener so the video will resume playback
videoInterval = setInterval(videoStatus, 100); // set the videoStatus interval to move the videoThumb with the video playback percentage
videoThumb.stopDrag(); // tells the videoThumb to stop draggin with our mouse
}

Test your movie; the video should play and you should be able to scrub the video now.

Conclusion

This first part was mostly spent setting up the ground work and getting some basic functionality going. In the next next chapter we're going to prepare the thumbnails, set up the XML, change how our video loads the movies, get our three gallery buttons working, add items and thumbnails for categories and add our video items with their thumbnails.

There's plenty to get your teeth into, I hope you're enjoying it so far.

I work for a company in Boise Idaho as a Flash developer. I just got into writing code about year ago and absolutely love ActionScript 3. I also love snowboarding, HALO, and any hip hop music "HOVA for life!".
Follow me on Twitter: zackattack27