1. Code
  2. JavaScript

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

Scroll to top
25 min read

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.

Part 2

  • Setup our video thumbnails, category thumbnails, and featured video thumbnails.
  • Write the XML file.
  • Load the XML file in Flash.
  • Create category items in the right sidebar.
  • Preload category item thumbnails.
  • Gallery button functionality for right sidebar.
  • Create video items in the right sidebar.
  • Preload video item thumbnails.
  • Build a dynamic vertical scrollbar that shows when necessary and hides when it is not needed.
  • Play selected videos.

Part 3

  • Display the current time and total time below the player.
  • Home button functionality.
  • Set our video's width and height.
  • Center our video in the player window.
  • Check the XML file for any featured videos.
  • Add featured video items to Featured sub bar.
  • Preload featured video item thumbnails.
  • Add a dynamic horizontal scrollbar for the featured sub bar.

I did mention this in the classes, but I'd like to thank some people for their help with this tutorial.

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.

Page SetupPage SetupPage Setup

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.

Library ItemsLibrary ItemsLibrary Items

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:

1
2
import caurina.transitions.*; // import the tweener class for our transitions

3
import caurina.transitions.properties.FilterShortcuts; //  import the tweener filter shortcuts class

4
stage.scaleMode = StageScaleMode.NO_SCALE; // tell the stage not to scale our items

5
stage.align = StageAlign.TOP_LEFT; // set the stage to center in the top left of the .swf file

6
FilterShortcuts.init();  // initialize the filter shortcuts for our tweener class

Step 4: Name Objects on Stage

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

1
2
var videoBox:MovieClip = player_mc;  // this will target the player mc on the main stage

3
var sidebarBox:MovieClip = rightSidebar_mc; // target the right sidebar mc on the main stage

4
var featuredBox:MovieClip = featuredBox_mc; // target the featured box mc on the main stage

5
var featuredBoxBg:MovieClip = featuredBox_mc.featuredBoxBg_mc;  // target the featured box's background in the featured box

Step 5: Center Content on Start up

Below what we have written so far, type:

1
2
setMyStage(); // listener for page startup

3
function setMyStage():void
4
{
5
	videoBox.x = stage.stageWidth / 2 - (featuredBoxBg.width / 2);  // position videoBox's x location

6
	videoBox.y = (stage.stageHeight / 2 - videoBox.height / 2) - featuredBoxBg.height / 2; // position videoBox's y location

7
	sidebarBox.x = (stage.stageWidth / 2 + 92);  // position sidebarBox's x location

8
	sidebarBox.y = videoBox.y;  // position sidebarBox's y location based on the videoBox's y location

9
	featuredBox.x = videoBox.x;  // position featuredBox's x location based on videoBox's x location

10
	featuredBox.y = videoBox.y + videoBox.height + 4; // position featuredBox's y location based on videoBox's y location

11
}

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.

1
2
stage.addEventListener(Event.RESIZE, myResizeEvent);  // add a listener to the stage to run a function when the stage width or height changes

3
function myResizeEvent(event:Event):void  //  run the function to handle stage width and height resize

4
{
5
	videoBox.x = stage.stageWidth / 2 - (featuredBoxBg.width / 2);
6
	videoBox.y = (stage.stageHeight / 2 - videoBox.height / 2) - featuredBoxBg.height / 2;
7
	sidebarBox.x = (stage.stageWidth / 2 + 92);
8
	sidebarBox.y = videoBox.y;
9
	featuredBox.x = videoBox.x;
10
	featuredBox.y = videoBox.y + videoBox.height + 4;
11
}

Now if you test your .swf file it will center on startup and if you change the width or height it will stay centered as well.

Step 7: Variables for Video Items on the Stage

Again let's add some vars so our instance names are not so long.

1
2
var playBtn:MovieClip = player_mc.playBtn_mc;  //  targets the play button in the player

3
var pauseBtn:MovieClip = player_mc.pauseBtn_mc;  //  targets the pause button in the player

4
var stopBtn:MovieClip = player_mc.stopBtn_mc;  //  targets the stop button in the player

5
var videoBlackBox:MovieClip = player_mc.videoBlackBox_mc;  //  targets the black background box in the player

6
var videoPreloader:MovieClip = player_mc.videoPreloader_mc;  //  targets the video preloader in the player

7
var videoTitleTxt:TextField = player_mc.VideoTitle_txt;  //  targets the dynamic text that will display the video title

8
var videoTimeTxt:TextField = player_mc.videoTime_txt;  //  targets the dynamic text layer that will display time played and total time

9
var videoThumb:MovieClip = player_mc.videoTrack_mc.videoThumb_mc;  //  targets the video scrubber thumb

10
var videoTrackProgress:MovieClip = player_mc.videoTrack_mc.videoTrackProgress_mc;  //  targets the video progress bar

11
var videoTrackDownload:MovieClip = player_mc.videoTrack_mc.videoTrackDownload_mc;  //  targets the video download percentage bar

12
var volumeThumb:MovieClip = player_mc.volumeSlider_mc.volumeThumb_mc;  // targets the volume scrubber thumb

13
var volumeTrack:MovieClip = player_mc.volumeSlider_mc.volumeTrackFull_mc;  //  targets the volume scrubber track percentage bar

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?

1
2
playBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
3
playBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
4
pauseBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
5
pauseBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
6
stopBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
7
stopBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
8
videoThumb.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
9
videoThumb.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
10
volumeThumb.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
11
volumeThumb.addEventListener(MouseEvent.MOUSE_OUT, btnOut);

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.

1
2
function btnOver(event:MouseEvent):void
3
{
4
	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

5
}
6
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

7
{
8
	event.currentTarget.gotoAndPlay("out");
9
}

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.)

Button Code And LabelsButton Code And LabelsButton Code And Labels

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.

Finished ButtonFinished ButtonFinished Button

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.

1
2
playBtn.mouseChildren = false;  //  makes the elements inside the targeted movie clip unselectable

3
playBtn.buttonMode = true;  // gives the hand cursor when you hover over the movieclip

4
pauseBtn.mouseChildren = false;
5
pauseBtn.buttonMode = true;
6
stopBtn.mouseChildren = false;
7
stopBtn.buttonMode = true;
8
videoThumb.mouseChildren = false;
9
videoThumb.buttonMode = true;
10
volumeThumb.mouseChildren = false;
11
volumeThumb.buttonMode = true;

Now all your buttons in the player_mc movie clip should have rollover and rollout functionality when you test your movie.

Step 12: Start Up

Here we will hide the video preloader, set the video title dynamic text field to be blank, along with zeroing out the video time dynamic text layer. Type the following code below the code in step 10:

1
2
videoPreloader.visible = false;
3
videoTitleTxt.text = "";
4
videoTimeTxt.text = "0:00 / 0:00";

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:

1
2
var currentVideo:String;  //  this string will be used to play the current video selected

3
var videoWidth:Number = 500;  // this will set the width of the video object and can be changed later on

4
var videoHeight:Number = 400;  //  this will set the height of the video object and can be changed later on

5
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:

1
2
var video:Video = new Video(videoWidth, videoHeight);  //  create a new Video item and set its width and height

3
video.x = 0;  //  position the video's x position

4
video.y = 0;  //  position the video's y position

5
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:

1
2
var video:Video = new Video(videoWidth, videoHeight);  //  create a new Video item and set its width and height

3
video.x = 0;  //  position the video's x position

4
video.y = 0;  //  position the video's y position

5
videoBlackBox.addChild(video);  //  add the video item to the videoBlackBox movieclip in the player_mc movieclip

6
7
var nc:NetConnection = new NetConnection();  //  variable for a new NetConnection

8
nc.connect(null);  //  set the nc variable to null

9
var ns:NetStream = new NetStream(nc);  // create a variable for a new NetStream connection & connect it to the nc variable

10
ns.addEventListener(NetStatusEvent.NET_STATUS, myStatusHandler);  //  add a listener to the NetStream to listen for any changes that happen with the NetStream

11
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);  //  add a listener to the NetStream for any errors that may happen

12
13
video.attachNetStream(ns);  // attach the NetStream variable to the video object

14
var newMeta:Object = new Object();  // create a new object to handle the metaData

15
newMeta.onMetaData = onMetaData;  //  when we recieve MetaData, attach it to the newMeta object

16
ns.client = newMeta;  // attach the NetStream.client to the newMeta variable

17
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:

1
2
function asyncErrorHandler(Event:AsyncErrorEvent):void
3
{
4
	//trace(event.text);  // this will handle any errors with video playback

5
}
6
function myStatusHandler(event:NetStatusEvent):void
7
{
8
	//trace(event.info.code);  // this will handle any events that are fired when the video is playing back

9
	switch(event.info.code)  //  switch statement to handle the various events with the NetConnection

10
	{
11
		case "NetStream.Buffer.Full":  //  when our buffer is full fire the code below

12
			ns.bufferTime = 10;  // set buffer time to 10 seconds

13
			Tweener.addTween(videoPreloader, {alpha:0, time:.3});  // tween videoPreloaders alpha to 0

14
		break;
15
		case "NetStream.Buffer.Empty":  //  when our buffer is empty fire the code below

16
			ns.bufferTime = 10;  // set buffer time to 10 seconds

17
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});  // tween videoPreloaders alpha to 1

18
		break;
19
		case "NetStream.Play.Start":  //  when our video starts playing we fire the code below

20
			ns.bufferTime = 10;  // set the buffer time to 10 seconds

21
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});  //  tween videoPreloaders alpha to 1

22
		break;
23
		case "NetStream.Seek.Notify":  // when you seek with the scrubber it sends a notify signal of the time

24
			ns.bufferTime = 10;  // set the buffer time to 10 seconds

25
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});  //  tween videoPreloaders alpha to 1

26
		break;
27
		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

28
			ns.bufferTime = 10;  // set the buffer time to 10 seconds

29
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});  //  tween videoPreloaders alpha to 1

30
		break;
31
		case "NetStream.Play.Stop":  // when you reach the end of the video

32
			Tweener.addTween(videoPreloader, {alpha:0, time:.3});  //  tween videoPreloaders alpha to 0

33
			ns.pause();  // pause the video

34
			ns.seek(1);  // seek the video to the first frame

35
		break;
36
	}
37
}
38
function onMetaData(newMeta:Object):void
39
{
40
	//trace("Metadata: duration=" + newMeta.duration + " width=" + newMeta.width + " height=" + newMeta.height + " framerate=" + newMeta.framerate);  // traces what it says

41
	duration = newMeta.duration;  // set the duration variable to the newMeta's duration

42
}

Step 17: Play the Video!

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

1
2
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.

1
2
playBtn.addEventListener(MouseEvent.CLICK, playBtnClick);  //  add a click listener to the playBtn

3
pauseBtn.addEventListener(MouseEvent.CLICK, pauseBtnClick);  // add a click listener to the pauseBtn

4
stopBtn.addEventListener(MouseEvent.CLICK, stopBtnClick);  // add a click listener to the stopBtn

Step 19: Add Playback Functions

1
2
function playBtnClick(event:MouseEvent):void
3
{
4
	ns.resume();  //  tell the NetStream to resume playback

5
}
6
function pauseBtnClick(event:MouseEvent):void
7
{
8
	ns.pause();  //  tell the NetStream to pause playback

9
}
10
function stopBtnClick(event:MouseEvent):void
11
{
12
	ns.pause();  //  tell the NetStream to pause playback

13
	ns.seek(0);  //  tell the NetStream to go to the first frame of the video

14
}

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.

1
2
var videoSound:SoundTransform;  //  variable to control the global sound in your movie

3
var volumeBounds:Rectangle;  //  variable to set the volume scrubber bounds

4
5
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.

1
2
videoSound = new SoundTransform();  // creates a new SoundTransform object

3
videoSound.volume = 1;  //  sets the SoundTransform object to 1 which is 100%

4
ns.soundTransform = videoSound;  //  links the video to the SoundTranform object

5
function volumeScrubberDown(event:MouseEvent):void
6
{
7
	volumeBounds = new Rectangle(0,0,75,0);  //  sets the bounds for the scrubber

8
	volumeThumb.startDrag(false, volumeBounds);  //  when you click and drag the volumeThumb movieclip it runs this function

9
	stage.addEventListener(MouseEvent.MOUSE_UP, volumeThumbUp);  //  add listener to the stage for when your mouse releases the click

10
	stage.addEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove);  //  add listener to the stage for when your mouse moves

11
}
12
function volumeThumbUp(event:MouseEvent):void
13
{
14
	volumeThumb.stopDrag();  //  stops the volumeThumb from being dragged

15
	stage.removeEventListener(MouseEvent.MOUSE_UP, volumeThumbUp);  //  remove this listener from the stage

16
	stage.removeEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove);  // remove this listener from the stage

17
}
18
function volumeThumbMove(event:MouseEvent):void
19
{
20
	volumeTrack.width = volumeThumb.x;  //  sets the blue bar in the volumeScrubber to the width of where the scrubber is

21
	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

22
	ns.soundTransform = videoSound;  //  actually transform the volume.

23
}

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:

1
2
var videoInterval = setInterval(videoStatus, 100);  // duration between intervals, in milliseconds

3
var amountLoaded:Number;  //  variable to tell us how much of the video has been loaded

4
var scrubInterval;  //  variable for the timeline scrubber

5
6
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.

1
2
function videoStatus():void
3
{
4
	amountLoaded = ns.bytesLoaded / ns.bytesTotal;  //  set our amountLoaded variable to a number that is the bytesLoaded divided by the bytesTotal of the video

5
	videoTrackDownload.width = amountLoaded * 340;  // sets the width of the videoTrackDownload bar to the amountLoaded var and multiply it by the track width.

6
	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

7
	videoTrackProgress.width = videoThumb.x;  // changes the width of the videoTrackProgress bar to the x location of the videoThumb

8
}
9
function videoScrubberDown(event:MouseEvent):void
10
{
11
	var bounds:Rectangle = new Rectangle(0,0,340,0);  //  sets the bounds for the video scrubber based on the width of the scrubber

12
	clearInterval(videoInterval);  //  clear our videoInterval so we can scrub 

13
	scrubInterval = setInterval(scrubTimeline, 10);  //  sets the scrubTimeline listener to update the video

14
	videoThumb.startDrag(false, bounds);  //  starts to drag the videoThumb within the bounds we set

15
	stage.addEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo);  //  add listener to the stage to listen for when we release the mouse

16
}
17
function scrubTimeline():void
18
{
19
	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

20
}
21
function stopScrubbingVideo(Event:MouseEvent):void
22
{
23
	stage.removeEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo);  // removes this listener when we release the mouse

24
	clearInterval(scrubInterval);  //  clears the scrubInterval listener so the video will resume playback

25
	videoInterval = setInterval(videoStatus, 100);  //  set the videoStatus interval to move the videoThumb with the video playback percentage

26
	videoThumb.stopDrag();  //  tells the videoThumb to stop draggin with our mouse

27
}

Your final code for this lesson should look like this:

1
2
//////  IMPORT CLASSES AND SET STAGE PROPERTIES  //////

3
import caurina.transitions.*;
4
import caurina.transitions.properties.FilterShortcuts;
5
stage.scaleMode = StageScaleMode.NO_SCALE;
6
stage.align = StageAlign.TOP_LEFT;
7
FilterShortcuts.init();
8
9
////// MAIN STAGE MOVIE CLIPS //////

10
var videoBox:MovieClip = player_mc;
11
var sidebarBox:MovieClip = rightSidebar_mc;
12
var featuredBox:MovieClip = featuredBox_mc;
13
var featuredBoxBg:MovieClip = featuredBox_mc.featuredBoxBg_mc;
14
15
////// VIDEO MOVIE CLIPS //////

16
var playBtn:MovieClip = player_mc.playBtn_mc;
17
var pauseBtn:MovieClip = player_mc.pauseBtn_mc;
18
var stopBtn:MovieClip = player_mc.stopBtn_mc;
19
var videoBlackBox:MovieClip = player_mc.videoBlackBox_mc;
20
var videoPreloader:MovieClip = player_mc.videoPreloader_mc;
21
var videoTitleTxt:TextField = player_mc.VideoTitle_txt;
22
var videoTimeTxt:TextField = player_mc.videoTime_txt;
23
var videoThumb:MovieClip = player_mc.videoTrack_mc.videoThumb_mc;
24
var videoTrackProgress:MovieClip = player_mc.videoTrack_mc.videoTrackProgress_mc;
25
var videoTrackDownload:MovieClip = player_mc.videoTrack_mc.videoTrackDownload_mc;
26
var volumeThumb:MovieClip = player_mc.volumeSlider_mc.volumeThumb_mc;
27
var volumeTrack:MovieClip = player_mc.volumeSlider_mc.volumeTrackFull_mc;
28
29
////// VIDEO VARS //////

30
var currentVideo:String;
31
var videoWidth:Number = 500;
32
var videoHeight:Number = 400;
33
var videoInterval = setInterval(videoStatus, 100);
34
var amountLoaded:Number;
35
var duration:Number;
36
var scrubInterval;
37
var videoSound:SoundTransform;
38
var volumeBounds:Rectangle;
39
40
////// FILE STARTUP //////

41
videoPreloader.visible = false;
42
videoTitleTxt.text = "";
43
videoTimeTxt.text = "0:00 / 0:00";
44
playBtn.mouseChildren = false;
45
playBtn.buttonMode = true;
46
pauseBtn.mouseChildren = false;
47
pauseBtn.buttonMode = true;
48
stopBtn.mouseChildren = false;
49
stopBtn.buttonMode = true;
50
videoThumb.mouseChildren = false;
51
videoThumb.buttonMode = true;
52
volumeThumb.mouseChildren = false;
53
volumeThumb.buttonMode = true;
54
55
////// SET STAGE //////

56
setMyStage();
57
stage.addEventListener(Event.RESIZE, myResizeEvent);
58
59
////// VIDEO EVENT LISTENERS //////

60
playBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
61
playBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
62
playBtn.addEventListener(MouseEvent.CLICK, playBtnClick);
63
pauseBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
64
pauseBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
65
pauseBtn.addEventListener(MouseEvent.CLICK, pauseBtnClick);
66
stopBtn.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
67
stopBtn.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
68
stopBtn.addEventListener(MouseEvent.CLICK, stopBtnClick);
69
videoThumb.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
70
videoThumb.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
71
videoThumb.addEventListener(MouseEvent.MOUSE_DOWN, videoScrubberDown);
72
volumeThumb.addEventListener(MouseEvent.MOUSE_OVER, btnOver);
73
volumeThumb.addEventListener(MouseEvent.MOUSE_OUT, btnOut);
74
volumeThumb.addEventListener(MouseEvent.MOUSE_DOWN, volumeScrubberDown);
75
76
////// VIDEO CODE //////

77
var video:Video = new Video(videoWidth, videoHeight);
78
video.x = 0;
79
video.y = 0;
80
videoBlackBox.addChild(video);
81
var nc:NetConnection = new NetConnection();
82
nc.connect(null);
83
var ns:NetStream = new NetStream(nc);
84
ns.addEventListener(NetStatusEvent.NET_STATUS, myStatusHandler);
85
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
86
video.attachNetStream(ns);
87
var newMeta:Object = new Object();
88
newMeta.onMetaData = onMetaData;
89
ns.client = newMeta;
90
ns.bufferTime = 5;
91
92
function asyncErrorHandler(Event:AsyncErrorEvent):void
93
{
94
	//trace(event.text);

95
}
96
function myStatusHandler(event:NetStatusEvent):void
97
{
98
	//trace(event.info.code);

99
	switch(event.info.code)
100
	{
101
		case "NetStream.Buffer.Full":
102
			ns.bufferTime = 10;
103
			Tweener.addTween(videoPreloader, {alpha:0, time:.3});
104
		break;
105
		case "NetStream.Buffer.Empty":
106
			ns.bufferTime = 10;
107
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});
108
		break;
109
		case "NetStream.Play.Start":
110
			ns.bufferTime = 10;
111
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});
112
		break;
113
		case "NetStream.Seek.Notify":
114
			ns.bufferTime = 10;
115
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});
116
		break;
117
		case "NetStream.Seek.InvalidTime":
118
			ns.bufferTime = 10;
119
			Tweener.addTween(videoPreloader, {alpha:1, time:.3});
120
		break;
121
		case "NetStream.Play.Stop":
122
			Tweener.addTween(videoPreloader, {alpha:0, time:.3});
123
			ns.pause();
124
			ns.seek(1);
125
		break;
126
	}
127
}
128
function onMetaData(newMeta:Object):void
129
{
130
	//trace("Metadata: duration=" + newMeta.duration + " width=" + newMeta.width + " height=" + newMeta.height + " framerate=" + newMeta.framerate);

131
	duration = newMeta.duration;
132
}
133
ns.play("flv/bsu-football-open.flv");
134
135
////// VIDEO BTN FUNCTIONS  //////

136
function playBtnClick(event:MouseEvent):void
137
{
138
	ns.resume();
139
}
140
function pauseBtnClick(event:MouseEvent):void
141
{
142
	ns.pause();
143
}
144
function stopBtnClick(event:MouseEvent):void
145
{
146
	ns.pause();
147
	ns.seek(0);
148
}
149
150
////// VOLUME SCRUBBER //////

151
videoSound = new SoundTransform();
152
videoSound.volume = 1;
153
ns.soundTransform = videoSound;
154
function volumeScrubberDown(event:MouseEvent):void
155
{
156
	volumeBounds = new Rectangle(0,0,75,0);
157
	volumeThumb.startDrag(false, volumeBounds);
158
	stage.addEventListener(MouseEvent.MOUSE_UP, volumeThumbUp);
159
	stage.addEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove);
160
}
161
function volumeThumbUp(event:MouseEvent):void
162
{
163
	volumeThumb.stopDrag();
164
	stage.removeEventListener(MouseEvent.MOUSE_UP, volumeThumbUp);
165
	stage.removeEventListener(MouseEvent.MOUSE_MOVE, volumeThumbMove);
166
}
167
function volumeThumbMove(event:MouseEvent):void
168
{
169
	volumeTrack.width = volumeThumb.x;
170
	videoSound.volume = (volumeThumb.x) / 50;
171
	ns.soundTransform = videoSound;
172
}
173
174
////// TIMELINE SCRUBBER //////

175
function videoStatus():void
176
{
177
	amountLoaded = ns.bytesLoaded / ns.bytesTotal;
178
	videoTrackDownload.width = amountLoaded * 340;
179
	videoThumb.x = ns.time / duration * 340;
180
	videoTrackProgress.width = videoThumb.x;
181
}
182
function videoScrubberDown(event:MouseEvent):void
183
{
184
	var bounds:Rectangle = new Rectangle(0,0,340,0);
185
	clearInterval(videoInterval);
186
	scrubInterval = setInterval(scrubTimeline, 10);
187
	videoThumb.startDrag(false, bounds);
188
	stage.addEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo);
189
}
190
function scrubTimeline():void
191
{
192
	ns.seek(Math.floor((videoThumb.x / 340) * duration));
193
}
194
function stopScrubbingVideo(Event:MouseEvent):void
195
{
196
	stage.removeEventListener(MouseEvent.MOUSE_UP, stopScrubbingVideo);
197
	clearInterval(scrubInterval);
198
	videoInterval = setInterval(videoStatus, 100);
199
	videoThumb.stopDrag();
200
}
201
202
////// BTN OVER & OUT FUNCTIONS //////

203
function btnOver(event:MouseEvent):void
204
{
205
	event.currentTarget.gotoAndPlay("over");
206
}
207
function btnOut(event:MouseEvent):void
208
{
209
	event.currentTarget.gotoAndPlay("out");
210
}
211
212
////// POSITION CONTENT //////

213
function setMyStage():void
214
{
215
	videoBox.x = stage.stageWidth / 2 - (featuredBoxBg.width / 2);
216
	videoBox.y = (stage.stageHeight / 2 - videoBox.height / 2) - featuredBoxBg.height / 2;
217
	sidebarBox.x = (stage.stageWidth / 2 + 92);
218
	sidebarBox.y = videoBox.y;
219
	featuredBox.x = videoBox.x;
220
	featuredBox.y = videoBox.y + videoBox.height + 4;
221
222
}
223
function myResizeEvent(event:Event):void
224
{
225
	videoBox.x = stage.stageWidth / 2 - (featuredBoxBg.width / 2);
226
	videoBox.y = (stage.stageHeight / 2 - videoBox.height / 2) - featuredBoxBg.height / 2;
227
	sidebarBox.x = (stage.stageWidth / 2 + 92);
228
	sidebarBox.y = videoBox.y;
229
	featuredBox.x = videoBox.x;
230
	featuredBox.y = videoBox.y + videoBox.height + 4;
231
}

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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.