RSS
Flash Effect Components

How to build a Flash Actionscript 3.0 Videoplayer

Wed, Jul 30, 2008

Audio & Video, Flash, Interfaces, Tutorials

How to build a Flash Actionscript 3.0 Videoplayer

Today we explain you how to create a videoplayer with some basic features like this one.

These are: - Play/Pause - Stop - Preloading - Scrubbing - Volume handling There will be another tutorial, which will extend this player. So be sure to check it out.

Requirements

Adobe Flash CS3

Try / Buy

Source Files

Download

Constants

As always, we begin with setting the constants. The BUFFER_TIME constant stores the time to buffer for the video in seconds. This one will later be assigned to the netstream object

const BUFFER_TIME:Number				= 8;

DEFAULT_VOLUME holds the start volume when the player starts

const DEFAULT_VOLUME:Number				= 0.6;

Our player has a timer, that updates all the visual parts. We store the update delay in milliseconds in a constant.

const DISPLAY_TIMER_UPDATE_DELAY:int			= 10;

To make the video a bit smoother, we can the the Video.smoothing variable to true. This may slow down old computers. If you want to deactivate the smoothing on runtime, just open the html file in the zip file, right click on the video player and choose low for the quality. This way the smoothing will automatically be deactivated by the flash player.

const SMOOTHING:Boolean	= true;

Variables

Let’s move on with the variables. We need to know, if the flv has been loaded when clicking the play button in order to load it or just play the video.

var bolLoaded:Boolean	= false;

For the timer function we need to know, if we’re currently scrubbing the volume or the progress bar.

var bolVolumeScrub:Boolean	= false;
var bolProgressScrub:Boolean	 = false;

Our player has also a mute/unmute button. So, we need to store the last used volume. Like this when you click on unmute, the scrubber will jump back to it’s previous position as the volume does. This value is always greater than zero. We asign the value from DEFAULT_VOLUME.

var intLastVolume:Number				= DEFAULT_VOLUME;

Then we need to have a net connection object for net stream and of course also a net stream object.

var ncConnection:NetConnection;
var nsStream:NetStream;

To store the received meta data from the flv file, we create an object

var objInfo:Object;

You can change your url to the flv file here. We just set it to the sample movie that’s in the same folder as the swf.

var strSource:String = "hancock-tsr2_h480p.flv";

And last of all, we create a timer object for updating the stuff from the player.

var tmrDisplay:Timer;

Functions

Now we need to initialize our player. First of all, we hide the unmute and pause button. Then we set the width of the progress and preload fill to 1.Our next step is adding a global eventlistener when the mouse button is released and adding event listeners to all buttons. Then we create ourtimer object for
updating all parts of the player and add the event listener. Next we create a new net connection, add the event listener and connect it to null because we don’t have a media server. The net stream object needs the net connection for initializing. Once we have our net stream object ready, we add the event listener, set the client property to this for handling the meta data and set buffer time to the value from the constant BUFFER_TIME. Then we attach the net stream to the video object on the stage and set the smoothing property to the value from the constant SMOOTHING. Last of all we set the default volume to the value from the constant DEFAULT_VOLUME. Note that only values from zero to one are allowed.

function initVideoPlayer():void {
	mcVideoControls.btnUnmute.visible	= false;
	mcVideoControls.btnPause.visible	= false;

	mcVideoControls.mcProgressFill.mcFillRed.width	= 1;
	mcVideoControls.mcProgressFill.mcFillGrey.width = 1;

	stage.addEventListener( MouseEvent.MOUSE_UP, mouseReleased);

	mcVideoControls.btnPause.addEventListener(MouseEvent.CLICK, pauseClicked);
	mcVideoControls.btnPlay.addEventListener(MouseEvent.CLICK, playClicked);
	mcVideoControls.btnStop.addEventListener(MouseEvent.CLICK, stopClicked);
	mcVideoControls.btnMute.addEventListener(MouseEvent.CLICK, muteClicked);
	mcVideoControls.btnUnmute.addEventListener(MouseEvent.CLICK, unmuteClicked);
	mcVideoControls.mcVolumeScrubber.btnVolumeScrubber.addEventListener(MouseEvent.MOUSE_DOWN, volumeScrubberClicked);
	mcVideoControls.mcProgressScrubber.btnProgressScrubber.addEventListener(MouseEvent.MOUSE_DOWN, progressScrubberClicked);

	tmrDisplay = new Timer(DISPLAY_TIMER_UPDATE_DELAY);
	tmrDisplay.addEventListener(TimerEvent.TIMER, updateDisplay);

	ncConnection = new NetConnection();
	ncConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
	ncConnection.connect(null);

	nsStream = new NetStream(ncConnection);
	nsStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
	nsStream.client = this;
	nsStream.bufferTime = BUFFER_TIME;

	vidDisplay.attachNetStream(nsStream);
	vidDisplay.smoothing = SMOOTHING;

	mcVideoControls.mcVolumeScrubber.x		= (53 * DEFAULT_VOLUME) + 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= mcVideoControls.mcVolumeScrubber.x - 394 + 53;
	setVolume(DEFAULT_VOLUME);
}

The most important part is now done. We’ve set all variables and added all event listeners. We’re now going to go through all button event listeners. When the user hit’s the play button, we need to check, if the flv download has already begun. If that’s the case, we resume the playback with the NetStream.resume() function. If not, we call the play() function and add the source to the flv file as the parameter.
Then we show the video display object that’s on the stage. And finally we switch the pause/play visibility.

function playClicked(e:MouseEvent):void {
	if(!bolLoaded) {
		nsStream.play(strSource);
		bolLoaded = true;
	} else {
		nsStream.resume();
	}

	vidDisplay.visible			= true;

	mcVideoControls.btnPause.visible	= true;
	mcVideoControls.btnPlay.visible		= false;
}

The pause button only calls the pause() function from the net stream object and switches the pause/play visibility.

function pauseClicked(e:MouseEvent):void {
	nsStream.pause();

	mcVideoControls.btnPause.visible	= false;
	mcVideoControls.btnPlay.visible		= true;
}

When the user click’s the play button, the stopVideoPlayer() function will be called. We’ll explain this function below.

function stopClicked(e:MouseEvent):void {
	stopVideoPlayer();
}

The mute button sets the volume to zero and updates the volume scrubber and fill position/width.

function muteClicked(e:MouseEvent):void {
	setVolume(0);

	mcVideoControls.mcVolumeScrubber.x		= 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= 1;
}

The unmute button sets the volume to the last used volume and updates the volume scrubber and fill position/width.

function unmuteClicked(e:MouseEvent):void {
	setVolume(intLastVolume);

	mcVideoControls.mcVolumeScrubber.x		= (53 * intLastVolume) + 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= mcVideoControls.mcVolumeScrubber.x - 394 + 53;
}

When the volume scrubber is clicked, the scrub flag will be set to true. Then we start dragging it withing the boundings that are described as a rectangle.
Exactly the same goes for the progress scrubber except that we’re setting another flag variable and bounding.

function volumeScrubberClicked(e:MouseEvent):void {
	bolVolumeScrub = true;

	mcVideoControls.mcVolumeScrubber.startDrag(false, new Rectangle(341, 19, 53, 0));
}

function progressScrubberClicked(e:MouseEvent):void {
	bolProgressScrub = true;

	mcVideoControls.mcProgressScrubber.startDrag(false, new Rectangle(0, 2, 432, 0));
}

Last of all, we have our mouseReleased() handler. This function is needed for knowing, when the user stops the scrubbing. First, we set the progress/volume scrub flag to false. Then we stop all dragging actions and update the width of the progress/volume fill. And if the volume is greater than zero, we store it in the variable intLastVolume.

function mouseReleased(e:MouseEvent):void {
	bolVolumeScrub		= false;
	bolProgressScrub	= false;

	mcVideoControls.mcProgressScrubber.stopDrag();
	mcVideoControls.mcVolumeScrubber.stopDrag();

	mcVideoControls.mcProgressFill.mcFillRed.width	= mcVideoControls.mcProgressScrubber.x + 5;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= mcVideoControls.mcVolumeScrubber.x - 394 + 53;

	if((mcVideoControls.mcVolumeScrubber.x - 341) / 53 > 0)
		intLastVolume = (mcVideoControls.mcVolumeScrubber.x - 341) / 53;
}

The updateDisplay() function will be called by the timer object 100 times a second. If you want, you can decrease this value by increasing the value from the constant DISPLAY_TIMER_UPDATE_DELAY.
First of all, we check if the user is scrubbing on the progress bar. If that’s the case, we seek in the video. If not, we just update the position of the scrubber according to the current time.
Then we set the time and duration label. We format the values with the function formatTime() which we explain later.
Now we update the width from the progress bar. The grey one displays the loading progress while the red one shows the progress from the video.
Last of all we update the volume and the red fill width when the user is scrubbing.

function updateDisplay(e:TimerEvent):void {
	if(bolProgressScrub)
		nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 432))
	else
		mcVideoControls.mcProgressScrubber.x = nsStream.time * 432 / objInfo.duration; 

	mcVideoControls.lblTimeDuration.htmlText 	= "" + formatTime(nsStream.time) + " / " + formatTime(objInfo.duration);

	mcVideoControls.mcProgressFill.mcFillRed.width	= mcVideoControls.mcProgressScrubber.x + 5;
	mcVideoControls.mcProgressFill.mcFillGrey.width	= nsStream.bytesLoaded * 438 / nsStream.bytesTotal;

	if(bolVolumeScrub) {
		setVolume((mcVideoControls.mcVolumeScrubber.x - 341) / 53);
		mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;
	}
}

The onMetaDataFunction will be called as soon as the net stream object gets the meta stuff from the flv file. We store these informations in a object. Now can start the timer object because we have all the necessary data.

function onMetaData(info:Object):void {
	objInfo = info;

	tmrDisplay.start();
}

Once a net status event will be fired, the netStatusHandler() function will be called. The event holds the info code of the event type. We only need to handle NetStream.Play.StreamNotFound in case the stream is not found and NetStream.Play.Stop to know, when the video reached its end to stop the player with the stopVideoPlayer() function.

function netStatusHandler(event:NetStatusEvent):void {
	switch (event.info.code) {
		case "NetStream.Play.StreamNotFound":
			trace("Stream not found: " + strSource);
		break;
		case "NetStream.Play.Stop":
			stopVideoPlayer();
		break;
	}
}

There are 2 ways to stop the playback: One is clicking the stop button, the other is reaching the end of the video. That’s the reason why we’ve put this in a function. First we pause the netstream and set the playback position to zero. In order to clear the display where the last frame of the video will be shown we need to set the visibility to false. We can’t use the Video.clear() function since it has a bug. But this one has already been reported to adobe. This workaround works fine. Finlay we switch the play/button visibility.

function stopVideoPlayer():void {
	nsStream.pause();
	nsStream.seek(0);

	vidDisplay.visible			= false;

	mcVideoControls.btnPause.visible	= false;
	mcVideoControls.btnPlay.visible		= true;
}

To set the volume of the video we use the setVolume() function. First we create a soundtransform object with the value from the parameter. Then we assign this object to nsStream.soundTransform. And we hide or show the mute and unmute according to the volume. If it’s greater than zero, we show the mute button and vice versa.

function setVolume(intVolume:Number = 0):void {
	var sndTransform	= new SoundTransform(intVolume);
	nsStream.soundTransform	= sndTransform;

	if(intVolume > 0) {
		mcVideoControls.btnMute.visible		= true;
		mcVideoControls.btnUnmute.visible	= false;
	} else {
		mcVideoControls.btnMute.visible		= false;
		mcVideoControls.btnUnmute.visible	= true;
	}
}

The last function formatTime() is used to format the seconds to the format mm:ss.

function formatTime(t:int):String {
	var s:int = Math.round(t);
	var m:int = 0;
	if (s > 0) {
		while (s > 59) {
			m++;
			s -= 60;
		}
		return String((m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
	} else {
		return "00:00";
	}
}

Call init function

The only thing left to do is calling the init function for the player.

initVideoPlayer();

We hope you liked this tutorial. If you have any question don’t hesitate to ask. Also we’ve already mentioned be sure to check back for the next part that will be coming soon.

Full code with comments

// ##########################
// ############# CONSTANTS
// ##########################

// time to buffer for the video in sec.
const BUFFER_TIME:Number				= 8;
// start volume when initializing player
const DEFAULT_VOLUME:Number				= 0.6;
// update delay in milliseconds.
const DISPLAY_TIMER_UPDATE_DELAY:int	= 10;
// smoothing for video. may slow down old computers
const SMOOTHING:Boolean					= true;

// ##########################
// ############# VARIABLES
// ##########################

// flag for knowing if flv has been loaded
var bolLoaded:Boolean					= false;
// flag for volume scrubbing
var bolVolumeScrub:Boolean				= false;
// flag for progress scrubbing
var bolProgressScrub:Boolean			= false;
// holds the last used volume, but never 0
var intLastVolume:Number				= DEFAULT_VOLUME;
// net connection object for net stream
var ncConnection:NetConnection;
// net stream object
var nsStream:NetStream;
// object holds all meta data
var objInfo:Object;
// url to flv file
var strSource:String					= "hancock-tsr2_h480p.flv";
// timer for updating player (progress, volume...)
var tmrDisplay:Timer;

// ##########################
// ############# FUNCTIONS
// ##########################

// sets up the player
function initVideoPlayer():void {
	// hide buttons
	mcVideoControls.btnUnmute.visible	= false;
	mcVideoControls.btnPause.visible	= false;

	// set the progress/preload fill width to 1
	mcVideoControls.mcProgressFill.mcFillRed.width = 1;
	mcVideoControls.mcProgressFill.mcFillGrey.width = 1;

	// add global event listener when mouse is released
	stage.addEventListener( MouseEvent.MOUSE_UP, mouseReleased);

	// add event listeners to all buttons
	mcVideoControls.btnPause.addEventListener(MouseEvent.CLICK, pauseClicked);
	mcVideoControls.btnPlay.addEventListener(MouseEvent.CLICK, playClicked);
	mcVideoControls.btnStop.addEventListener(MouseEvent.CLICK, stopClicked);
	mcVideoControls.btnMute.addEventListener(MouseEvent.CLICK, muteClicked);
	mcVideoControls.btnUnmute.addEventListener(MouseEvent.CLICK, unmuteClicked);
	mcVideoControls.mcVolumeScrubber.btnVolumeScrubber.addEventListener(MouseEvent.MOUSE_DOWN, volumeScrubberClicked);
	mcVideoControls.mcProgressScrubber.btnProgressScrubber.addEventListener(MouseEvent.MOUSE_DOWN, progressScrubberClicked);

	// create timer for updating all visual parts of player and add
	// event listener
	tmrDisplay = new Timer(DISPLAY_TIMER_UPDATE_DELAY);
	tmrDisplay.addEventListener(TimerEvent.TIMER, updateDisplay);

	// create a new net connection, add event listener and connect
	// to null because we don't have a media server
	ncConnection = new NetConnection();
	ncConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
	ncConnection.connect(null);

	// create a new netstream with the net connection, add event
	// listener, set client to this for handling meta data and
	// set the buffer time to the value from the constant
	nsStream = new NetStream(ncConnection);
	nsStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
	nsStream.client = this;
	nsStream.bufferTime = BUFFER_TIME;

	// attach net stream to video object on the stage
	vidDisplay.attachNetStream(nsStream);
	// set the smoothing value from the constant
	vidDisplay.smoothing = SMOOTHING;

	// set default volume
	mcVideoControls.mcVolumeScrubber.x = (52 * DEFAULT_VOLUME) + 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 52;
	setVolume(DEFAULT_VOLUME);
}

function playClicked(e:MouseEvent):void {
	// check's, if the flv has already begun
	// to download. if so, resume playback, else
	// load the file
	if(!bolLoaded) {
		nsStream.play(strSource);
		bolLoaded = true;
	}
	else{
		nsStream.resume();
	}

	// show video display
	vidDisplay.visible					= true;

	// switch play/pause visibility
	mcVideoControls.btnPause.visible	= true;
	mcVideoControls.btnPlay.visible		= false;
}

function pauseClicked(e:MouseEvent):void {
	// pause video
	nsStream.pause();

	// switch play/pause visibility
	mcVideoControls.btnPause.visible	= false;
	mcVideoControls.btnPlay.visible		= true;
}

function stopClicked(e:MouseEvent):void {
	// calls stop function
	stopVideoPlayer();
}

function muteClicked(e:MouseEvent):void {
	// set volume to 0
	setVolume(0);

	// update scrubber and fill position/width
	mcVideoControls.mcVolumeScrubber.x				= 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= 1;
}

function unmuteClicked(e:MouseEvent):void {
	// set volume to last used value
	setVolume(intLastVolume);

	// update scrubber and fill position/width
	mcVideoControls.mcVolumeScrubber.x = (53 * intLastVolume) + 341;
	mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;
}

function volumeScrubberClicked(e:MouseEvent):void {
	// set volume scrub flag to true
	bolVolumeScrub = true;

	// start drag
	mcVideoControls.mcVolumeScrubber.startDrag(false, new Rectangle(341, 19, 53, 0));
}

function progressScrubberClicked(e:MouseEvent):void {
	// set progress scrub flag to true
	bolProgressScrub = true;

	// start drag
	mcVideoControls.mcProgressScrubber.startDrag(false, new Rectangle(0, 2, 432, 0));
}

function mouseReleased(e:MouseEvent):void {
	// set progress/volume scrub to false
	bolVolumeScrub		= false;
	bolProgressScrub	= false;

	// stop all dragging actions
	mcVideoControls.mcProgressScrubber.stopDrag();
	mcVideoControls.mcVolumeScrubber.stopDrag();

	// update progress/volume fill
	mcVideoControls.mcProgressFill.mcFillRed.width	= mcVideoControls.mcProgressScrubber.x + 5;
	mcVideoControls.mcVolumeFill.mcFillRed.width	= mcVideoControls.mcVolumeScrubber.x - 394 + 53;

	// save the volume if it's greater than zero
	if((mcVideoControls.mcVolumeScrubber.x - 341) / 53 > 0)
		intLastVolume = (mcVideoControls.mcVolumeScrubber.x - 341) / 53;
}

function updateDisplay(e:TimerEvent):void {
	// checks, if user is scrubbing. if so, seek in the video
	// if not, just update the position of the scrubber according
	// to the current time
	if(bolProgressScrub)
		nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 432))
	else
		mcVideoControls.mcProgressScrubber.x = nsStream.time * 432 / objInfo.duration; 

	// set time and duration label
	mcVideoControls.lblTimeDuration.htmlText		= "" + formatTime(nsStream.time) + " / " + formatTime(objInfo.duration);

	// update the width from the progress bar. the grey one displays
	// the loading progress
	mcVideoControls.mcProgressFill.mcFillRed.width	= mcVideoControls.mcProgressScrubber.x + 5;
	mcVideoControls.mcProgressFill.mcFillGrey.width	= nsStream.bytesLoaded * 438 / nsStream.bytesTotal;

	// update volume and the red fill width when user is scrubbing
	if(bolVolumeScrub) {
		setVolume((mcVideoControls.mcVolumeScrubber.x - 341) / 53);
		mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;
	}
}

function onMetaData(info:Object):void {
	// stores meta data in a object
	objInfo = info;

	// now we can start the timer because
	// we have all the neccesary data
	tmrDisplay.start();
}

function netStatusHandler(event:NetStatusEvent):void {
	// handles net status events
	switch (event.info.code) {
		// trace a messeage when the stream is not found
		case "NetStream.Play.StreamNotFound":
			trace("Stream not found: " + strSource);
		break;

		// when the video reaches its end, we stop the player
		case "NetStream.Play.Stop":
			stopVideoPlayer();
		break;
	}
}

function stopVideoPlayer():void {
	// pause netstream, set time position to zero
	nsStream.pause();
	nsStream.seek(0);

	// in order to clear the display, we need to
	// set the visibility to false since the clear
	// function has a bug
	vidDisplay.visible			= false;

	// switch play/pause button visibility
	mcVideoControls.btnPause.visible	= false;
	mcVideoControls.btnPlay.visible		= true;
}

function setVolume(intVolume:Number = 0):void {
	// create soundtransform object with the volume from
	// the parameter
	var sndTransform	= new SoundTransform(intVolume);
	// assign object to netstream sound transform object
	nsStream.soundTransform	= sndTransform;
	// hides/shows mute and unmute button according to the
	// volume
	if(intVolume > 0) {
		mcVideoControls.btnMute.visible		= true;
		mcVideoControls.btnUnmute.visible	= false;
	} else {
		mcVideoControls.btnMute.visible		= false;
		mcVideoControls.btnUnmute.visible	= true;
	}
}

function formatTime(t:int):String {
	// returns the minutes and seconds with leading zeros
	// for example: 70 returns 01:10
	var s:int = Math.round(t);
	var m:int = 0;
	if (s > 0) {
		while (s > 59) {
			m++;
			s -= 60;
		}
		return String((m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
	} else {
		return "00:00";
	}
}

// ##########################
// ############# INIT PLAYER
// ##########################
initVideoPlayer();

About the Author


Rafael Nuenlist - who has written 7 posts on Flash Platform and ActionScript Tutorials.

Rafael Nünlist is currently working at orange8 as a Richmedia Developer. He will complete his apprenticeship with a swiss federal vocational diploma in information technology this summer. His strengths are Flash, Flex, Actionscript, Php/MySQL and AIR. He is also a member of the dreaminginflash team.

Enjoy this post?

Your vote will help us grow and provide even more awesomeness

  • Digg
  • Reddit
  • description
  • Design Float
  • del.icio.us
  • StumbleUpon
  • Mixx
  • TwitThis

86 Comments For This Post

  1. Lulu Says:

    Beautifully made tutorial! I appreciate your thoroughness.

    Not sure if you’re taking requests for that extended tutorial (hehe) but there is something that I’d love to be able to do that I can’t find a tutorial about.

    I’d like to be able to select a section of the video (designate start and end points along the timeline) to loop.

    Any thoughts?

  2. Bill Roughen Says:

    Your video player is terrific. I’ve been trying to find something like this for months. I downloaded the code and modified it for my flash project. Everything works perfectly. Now I have a new problem that maybe you can easily solve. My flash site uses one instance of the video display and one instance of the video controls across all the frames. When I want to show a video I make it visible and when I don’t need it I make it invisible. There are navigation buttons at the top to jump to various frames.

    I can get everything to behave when the navigation buttons are used. The video will stop, the visibility of the buttons is updated, etc. But when I click on the play button to start a new flv there is a brief frame at the beginning of the previous video. How can I clear the video player so the new stream will play without this problem?

    Thanks.

    Right now I’m using a progressive download. I’m using the close() method of the netstream to clear it, but the buffer still seems to contain the previous video.

  3. Rafael Nünlist Says:

    @Lulu: I have to disapoint you, I can’t include your request in the next part. But it shouldn’t be a problem to implement this functionality.

    @Bill Roughen: Mmmh, since the Video.clear() function doesn’t work, you will have to set the visibility of the video to false. As soon as the playpack starts, you can set it to true.
    Just adding a new case to the netStatusHandler() function should be enough:

    ================================

    function netStatusHandler(event:NetStatusEvent):void {
    // handles net status events
    switch (event.info.code) {
    // trace a messeage when the stream is not found
    case “NetStream.Play.StreamNotFound”:
    trace(”Stream not found: ” + strSource);
    break;

    // when the video reaches its end, we stop the player
    case “NetStream.Play.Stop”:
    stopVideoPlayer();
    break;

    case “NetStream.Play.Start”:
    vidDisplay.visible = true;
    break;
    }
    }

    ================================

    And be sure to comment the vidDisplay.visible line in the playClicked() function:
    =====================
    function playClicked(e:MouseEvent):void {
    // check’s, if the flv has already begun
    // to download. if so, resume playback, else
    // load the file
    if(!bolLoaded) {
    nsStream.play(strSource);
    bolLoaded = true;
    }
    else{
    nsStream.resume();
    }

    // show video display
    //vidDisplay.visible = true;

    // switch play/pause visibility
    mcVideoControls.btnPause.visible = true;
    mcVideoControls.btnPlay.visible = false;
    }
    ================

    Hope this works out.

    cheers

  4. COle Says:

    Love the player, one question. How do I make it start playing the second it loads instead of having to click on play?

  5. Rafael Nünlist Says:

    @COle: Thank you. To Autoplay you can just add the following line at the very end of the script (After initVideoPlayer()):

    playClicked(null);

    cheers

  6. sooraj Says:

    Excellent!!!!!!!!
    I had seen many players, but this one looks very good in look and functioning.
    I had a question, What are changes to the code when we using a Flash Media Server?
    ie; streaming from a media server.

  7. Rafael Nünlist Says:

    @sooraj: Thank you!
    When using a Flash Media Server you just need to set it to the net connection. So, the only change would be:

    ncConnection.connect(null);

    Which will then become:
    ncConnection.connect(”rtmp://example.com/”);

    That’s it.

  8. Craig Says:

    Great tutorial! Answers a lot of questions I’ve been struggling through with AS 3.0!

    Two quick questions, what is the method for stopping the video at a specific point, i.e. I want to hold on the last frame of the video file after it’s played through.

    And secondly, I’ve adapted the player for larger video dimensions and everything works great with the exception of the Progress Scrubber. I can restrain it to the new, longer progress bar, but every time the video starts, it jumps 200 or so pixels to the right. I know this is probably simple, I just don’t think I’m looking in the right place within the code.

    Thanks.

  9. Rafael Nünlist Says:

    Hey Craig

    Thank you for your feedback!
    If you want the video player to show the last frame you just need to comment this line:

    function netStatusHandler(event:NetStatusEvent):void {
    // handles net status events
    switch (event.info.code) {
    // trace a messeage when the stream is not found
    case “NetStream.Play.StreamNotFound”:
    trace(”Stream not found: ” + strSource);
    break;

    // when the video reaches its end, we stop the player
    case “NetStream.Play.Stop”:
    // ################# COMMENT THIS LINE HERE
    // stopVideoPlayer();
    break;
    }

    For the other thing you need to adjust the width of the progressbar in the code since it’s static:

    function updateDisplay(e:TimerEvent):void {
    // checks, if user is scrubbing. if so, seek in the video
    // if not, just update the position of the scrubber according
    // to the current time
    if(bolProgressScrub)
    nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 432))
    else
    mcVideoControls.mcProgressScrubber.x = nsStream.time * 432 / objInfo.duration;

    So, the number 432 represents how far the scrubber can go. Try to set this number to the width of the progress bar, this should help you out ;)

    Greetings
    Rafael

  10. Jake Rutter Says:

    Awesome site, I just found this. I have been adding flash sites to my rss feeds reader to keep up with things. This is a great tutorial, Im working on building my own AS3 Video Player so this definitely helps!

  11. Jake Rutter Says:

    One thing, had you thought about putting all of the code into a class? or into OOP?

  12. John Culshaw Says:

    Fantastic tutorial — best I have seen in a long time!

    I am having one problem using it in my SWF, though. In my SWF the user can toggle between looking at some still images, or a video. The still image viewing area and video area each take the entire stage area. That is, when viewing the still images, I hide all the video elements and vice versa (when viewing the video, I hide all still image elements).

    My problem is that when I first toggle to the video elements part (default is still image mode) everything works hunky dory with the video elements as expected. But, if I toggle back to still image mode and then try to go back to the video mode, the player is unresponsive.

    I have a feeling that the problem has something to do with trying to run the initVideoPlayer(); function after is has already been run once (at the very first toggle) — but some tests that I have run have been unsuccessful.

    The behavior I would love to have is that when toggling away from the video mode elements, the video pauses (I can handle this part) and the stream suspends while I am over in still image mode. When I toggle back to video mode, the video resumes and streaming picks up where it left off.

    Any ideas how this may be attained?

    Regards,

    -john

  13. Craig Says:

    Rafael,

    Thanks for the tips on how to stop the video on the last frame. Would I use the same type of technique to trigger another event after the video has finished playing?

    For example, I’m trying to program a “Play All” button for x number of FLVs. I imagine the function would detect the end of each video and then go to the next label on the timeline (or whatever code I put here I suppose).

    Thanks in advance for your help.

  14. Walmik Says:

    Hi Rafael,
    I do not have a query that is directly related to this tutorial but it is relevant here I hope. I m working on a site that is heavily animated and uses the flv playback component at various points in the animation. So for example a section loads with a lot of animation and comes to point and stops where a flv playback component is placed. The when another section is loaded, this section animates to its end and launches the ‘clicked’ sections animation which again goes through an elaborate animation and stops where it has a FLV Playback component on the stage which plays videos. And so on..

    The problem is, when a user has requested a section and the flv playback component is still to buffer/load the video, there can be some lag on a slower internet connection hence the user changes the section before any video content had reached his computer. After a few moments, the video that could not load earlier just starts to play abruptly without any component on the stage!

    While leaving a section I m checking if a flv is playing (flv.playing) and if so then stopping it. But since the video never loaded, this condition is not met. Also stopping video anyways results in an error as the script doesnt know what to stop.

    So what I wanted to know is, is there some way to stop all video like there was stop all sounds in earlier versions of AS? OR is there some way I can make sure that a video request is successfully terminated?

    Lastly I m terribly sorry if this query does not belong here. Many Thanks in advance AND of course… this is a gr8 tutorial… very straightforward.

  15. Carlos Pinho Says:

    Hi Walmik,

    No problem to post a query here. I will try to add a new feature at The Tech Labs, a place where you add your doubts and questions and where developers will try to help you.

    Cheers,
    Carlos

  16. Jim Says:

    Where do you instantiate the mcVideoControls object? I’m getting errors for undefined properties since

  17. grabek Says:

    YOU ARE AWESOME!
    you saved me like 50 hours of research. Your code is great!

  18. Roy Says:

    Your script is really cool and exactly what I was looking for.

    I tried to connect it to the sample vod file (sample.flv) on FMS using the modified code:
    ncConnection.connect(”rtmp://ip-address/vod”);
    But then i get an error:

    “ArgumentError: Error #2126: NetConnection object must be connected.
    at flash.net::NetStream/construct()
    at flash.net::NetStream()
    at videoplayer_fla::MainTimeline/initVideoPlayer()
    at videoplayer_fla::MainTimeline/frame1()”

    It can’t seem to connect.

    When i use the vodtest file everything works (on my server and development pc), but that one does not connect with the netConnection code.

    I hope you can help me.

    Best regards,

    Roy

  19. Sems Says:

    NetStream does not wait for the NetConnection to be established, when connecting to a Flash Media Server. So Roy, you’ll to move the NetStream code under netStatusHandler, as below (hope this displays fine):

    function netStatusHandler(event:NetStatusEvent):void {
    // handles net status events
    switch (event.info.code) {
    // trace a messeage when the stream is not found
    case “NetStream.Play.StreamNotFound”:
    trace(”Stream not found: ” + strSource);
    break;

    // when the video reaches its end, we stop the player
    case “NetStream.Play.Stop”:
    stopVideoPlayer();
    break;
    case “NetConnection.Connect.Success”:
    // create a new netstream with the net connection, add event
    // listener, set client to this for handling meta data and
    // set the buffer time to the value from the constant
    nsStream = new NetStream(ncConnection);
    nsStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nsStream.client = this;
    nsStream.bufferTime = BUFFER_TIME;

    // attach net stream to video object on the stage
    vidDisplay.attachNetStream(nsStream);
    // set the smoothing value from the constant
    vidDisplay.smoothing = SMOOTHING;

    // set default volume
    mcVideoControls.mcVolumeScrubber.x = (52 * DEFAULT_VOLUME) + 341;
    mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 52;
    setVolume(DEFAULT_VOLUME);
    //plus other stuff if you need.
    break;
    }
    }

  20. Roy Says:

    Hi Sems,

    Thanks.. i’ll look into it right away.

    Best regards,

    Roy

  21. mmdGuru Says:

    Hi Rafael,

    Great video player=) Think you did a awesome job…

    I’m trying to implement the player in a project. The project requires a skip video button to jump to another frame and when the video is finished it should also jump to the same frame as the skip function!

    can you please help me to get on the right track=)

    regards

    Thomas

  22. william Says:

    thanks for the tutorials. please am using AS2, can i use the code for it. if not, kindly send me a tutorials on that. am new to flash.

  23. Rafael Nünlist Says:

    @mmdguru: just call the same function that goes to the next frame from a skip button and also call it when the netstream event is fired for stop.
    :::::
    case “NetStream.Play.Stop”:
    callYourFunctionThatGoesToTheNextFrame();
    break;
    :::::

    @william: no, you can’t use the code for as2. but there are many video players out there made with as2 ;)

  24. Michael Dunn Says:

    Thanks for the tutorial, great videoplayer! I do have a question. I’m trying to connect to a FMS. Followed example from post Aug 8, 2008 4:43 pm and I get the following message:

    ArgumentError: Error #2126: NetConnection object must be connected.
    at flash.net::NetStream/flash.net:NetStream::construct()
    at flash.net::NetStream$iinit()
    at videoplayer_fla::MainTimeline/initVideoPlayer()
    at videoplayer_fla::MainTimeline/videoplayer_fla::frame1()

    I lost here, any ideas?
    thanks

  25. Kukurusta Says:

    Hi Rafael

    I can just repeat what other already said. This site is a gem.

    I’m getting my movies from a FMS. I had to adopt your player with the already mentioned function netStatusHandler(event:NetStatusEvent):void and add a not yet mentioned

    ncConnection.client = this;
    function onBWDone():void {
    trace(”onBWDone called”);
    }

    in order to catch all required callbacks.

    I’m now wondering why I receive a NetStream.Play.Stop notification after a while even if the videostream is paused.

    Any idea why this notification is fired?

    Fabio

  26. Kukurusta Says:

    Hi Rafael and all

    Again I’m getting my movies from a FMS with rtmp. I’d like to have the videostream pause when the player is loaded, but having the first frame displayed. How can I achieve that?

    Fabio

  27. Jimmy Says:

    I am trying your AS3 Videoplayer with red5 streaming server but i can not get it to work, i cant figure what i am doing worng. Is there anyway you can post or send me a working streaming copy i would greatly appreciate it

    You did a very nice job on the player.

    Jimmy

  28. Phil Says:

    This is fantastic! Very thorough tutorial.

    I wonder if anyone (more advanced than me) has managed to turn this into a class?

  29. dvesh Says:

    Great tutorial. Sometimes it’s hard getting all the pieces together in one place and you did an excellent job here.

  30. Alon Says:

    good work!!

    but i have a real problem to connect it to my fms server (influxis)
    i changed the code connect(”rtmp……”);
    and on play(”file”);

    and its always give me that:
    ArgumentError: Error #2126: NetConnection object must be connected.
    at flash.net::NetStream/flash.net:NetStream::construct()
    at flash.net::NetStream$iinit()
    at videoplayer_fla::MainTimeline/initVideoPlayer()

  31. Jason Says:

    Terrific. Has really helped me get up to speed with AS3. Question: I’m using your player inside of another swf and when I navigate away from the frame with the player the vid still plays. How can I get it to stop when a user navigates away?

  32. flashDuniya Says:

    var nc:NetConnection = new NetConnection();
    var ns:NetStream;
    nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
    nc.client = this;
    nc.connect(”rtmp://flashduniya.com/videos/”);

    function netStatusHandler(event:NetStatusEvent):void {

    switch (event.info.code) {
    case “NetConnection.Connect.Success” :
    connectVideo();
    var it:uint = setInterval(seeking, 100);
    setVolume(0);
    break;
    case “NetStream.Play.StreamNotFound” :
    trace(”Stream not found: ” + videoURLAr[selectedNum]);
    break;
    }
    }
    function connectVideo() {
    ns = new NetStream(connection);
    ns.client = this;
    videoObj.attachNetStream(ns);
    ns.play(”flashduniya”);
    }
    btnPause.addEventListener(MouseEvent.CLICK, pauseVideo);
    btnPlay.addEventListener(MouseEvent.CLICK, playVideo);
    function pauseVideo(e:MouseEvent):void {
    ns.pause();
    }
    function playVideo(e:MouseEvent):void {
    ns.resume();
    }

    This above code is working fine play pause functionality also working fine. But while we pause the video and after some time(about more than 10 min) we click on play button video start playing with beging not from the paused postion.

    Any one can tell me the solution of this problem.

    Thanks,
    FlashDuniya

  33. Matt Says:

    I love the video player that you have provided. I have tried to tweak it a little bit and am having a problem. I have changed it so that it works for 640×480 videos. I was able to change the size of the progress bar and was able to move it to the right some.

    The only thing that appears to be wrong is that when I click play the mcProgressScrubber starts over to the far left of the movie instead of 50px to the right where the actual scrubber bar is.

    Can anyone help?

    Thanks
    Matt

  34. Matt Says:

    Hello there,

    Let me start off by saying that this is something that I have been looking for for the past 3 years. So now that i have found something that is just what I am looking for, I want to make it easy and perfect. In saying that I have 1 question.

    Is there a way to link a different flv file into the player without going into flash every time?

  35. Josh Says:

    Hey man
    Im sortove new to flash been using it for about a year and a half now, but this is defo the best video player ive seen so dar :)

    cheers :)

  36. Josh Says:

    // for the previous comment.

    so far*

    my bad on the spelling mistake haha:)

  37. gary simms Says:

    Thanks for this tutorial! Just getting my hands dirty with AS3.
    Will be trying to move this all to a class soon.

    Hey Matt,
    Or others interested in not having to put the flv source in the flash itself. Simply use swfobject to embed your swf file.
    I’m using swfobject 1.5, haven’t dug in to v2.0 yet, but I’m sure it’s similar.

    First make sure you call the swfobject js in the head.

    HTML code edit, notice the variable I’m passing to flash.

    Looks like you don’t have the flash player. Get Flash Player

    var so = new SWFObject(”videoplayer.prt1.swf”, “FlashwindowName”, “440″, “365″, “9″, “#000000″);
    //so.addParam(”wmode”, “transparent”);
    so.addVariable(”videoPath”, “hancock-tsr2_h480p.flv”)
    so.write(”flashContent”);

    And in your fla file change the source variable line at top to this.

    // url to flv file
    var strSource:String = videoPath;

    That’s it, simple right?
    gary.

  38. gary simms Says:

    Shoot, blog stripped out the tags.
    What about this?

    head tag
    <script type=”text/javascript” src=”swfobject.js”></script>

    HTML code
    <body bgcolor=”#000000″>

    <div id=”flashContent”>
    <h1>Looks like you don’t have the flash player.</h1> <a href=”http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOX” rel=”external”>Get Flash Player</a>
    </div>

    <script type=”text/javascript”>
    var so = new SWFObject(”videoplayer.prt1.swf”, “FlashwindowName”, “440″, “365″, “9″, “#000000″);
    //so.addParam(”wmode”, “transparent”);
    so.addVariable(”videoPath”, “hancock-tsr2_h480p.flv”)
    so.write(”flashContent”);
    </script>

    </body>

  39. bill krings Says:

    Great tutorial, but I think I’m missing some fundamental knowledge. I am using Flash CS3 Pro. Where is the source for the instance of Display_vid? I know it is in the library associated with you file, but where did it originate from. Is this a component you created or is is in a Flash component library somewhere?
    thanks!

  40. apompei Says:

    Great tutorial!

    I am trying to add an image that will load and display before a user presses play. Once the user presses play I’d like for the image to be removed from the display list so the video is in view.

    In the variables section I added a new loader object with an eventListerner listening for the COMPLETE event that then calls a function that adds the image to the displayList. Following this eventListener I have the load constructor with the required URLRequest pointing to the JPEG image I am loading. This all works but I can’t figure out how to remove the image.

    Where I am falling short is when the user clicks the play button how that can call a function that will remove the loader and the associated JPEG from the list. The lay button already is call the playClicked function. Is it possible to have it call two functions?

    I am at really at a lose here any help would be appreciated.

  41. knalle Says:

    BTW, if you want to OOP this into a class quick and dirty, then just import the following in your class:

    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.events.NetStatusEvent;
    import flash.geom.Rectangle;
    import flash.media.SoundTransform;

    and make all funtions private
    The only problem I had was that onMetaData needed to be public.

  42. Ben Says:

    Hi, after loosing a week on trying to make a nice FLV player, i came across yours ! Wich is wonderful

    But..
    It works in my projet, but only on the first frame. When i put it
    inside a section that i call later using addChild, it doesn’t load.

    I’ve tried with a new document and it work…

    Could it be a variable, or else that i have to do so it work ?

    I think i’m not that clear… ;)

  43. Joe Says:

    Where does the number 53 come from?

  44. knalle Says:

    I dunno. Never heard of that number until now.

  45. LeonD Says:

    hey there, i love your player and it works like a charme. i have a general question. when i jump to the frame that includes the player, the player works like it should, but when i go to another frame while the player is still playing, it doesnt stop, it keeps on playing in the background until the video ends. is there some way to unload the player when leaving the frame, so it doesnt keep on working in the backgound? thx in advance

  46. Rafael Nünlist Says:

    @ LeonD: Before you jump to the next frame, just stop the player with the stopVideoPlayer() function ;)

    stopVideoPlayer();
    gotoAndStop(”yourFrameLabelOrFrameNuber”);

  47. Sean Says:

    This is great! Very well done. Left me with one question though… How difficult would it be to have multiple instances of the player on the stage? Im guessing putting the controls and video windows into some sort of array?

  48. Rafael Nünlist Says:

    @ Sean: You can put all the code & visuals into a separate movieclip make several instances of it and place them on the stage. Or you can convert the code into a class and do the instantiation programmatically.

  49. LeonD Says:

    @rafael thx it worked great. but now i have some other problem. i had to put the player and his code in an mc. whenever i need the player i put the mc with the player on the stage. but when i say stopVideoPlayer () one the main stage codeline it tells me that there is no VideoPlayer function. now i understand why it tells me that but how can i stop the player within that mc from the main timeline?

  50. Rafael Nünlist Says:

    @ LeonD: Just give your mc a name by clicking on it and changing the value in the properties. On the main timeline you’d write something like this to stop it:

    myVideoPlayerInstance.stopVideo();

    Of course “myVideoPlayerInstance” would be the name of your movieclip.

    cheers

  51. petit Says:

    Hello Raf!

    Thanx for sharing. One think i like is that you can easily customize the design (which is not the case for the FLVplayer that comes with flash for instance but you probably noticed..).

    One feature though i think is missing and would bring your player near perfection…:)

    ==> Show & hide the controls when you mouse over/out the player!

    I’ve been trying to code this for some hours but i’m not a AS3 wizard yet and get jerky results.

    If anyone could give it a try …Thanx a lot.
    Best regards.

  52. Rafael Nünlist Says:

    @petit: Just add an event listener to the whole mcControls for mouseOver and mouseOut and show or hide it ;)

    Like this:

    mcControls.addEventListener(MouseEvent.MOUSE_OVER, showHideControls);
    mcControls.addEventListener(MouseEvent.MOUSE_OUT, showHideControls);

    function showHideControls(e:MouseEvent):void {
    if(e.type == MouseEvent.MOUSE_OVER)
    mcControls.alpha = 1;
    else
    mcControls.alpha = 0;
    }

  53. codo Says:

    very nice!!

  54. petit Says:

    Well done Raf, you’re my hero today:)

    i tried with mcVidecontrols.visible= false/true but for some reasons it gives jerky behaviours, did not think to use .alpha

    tip: If you want the controls & the video to react to mouse over/out you can put an invisible layer in the mcVideoControl of the size of the video…
    Thanx Again.

  55. LeonD Says:

    is it possible that the video frame shows a preview picture of the video before you hit the play button and how would you do that?

  56. Rafael Nünlist Says:

    @ LeonD: You could make a screenshot from your video, save it as a jpg/png/gif and the load it with the Loader class in the video player. Or you create a serverside script that does the screenshot job for you and returns the image.
    I’d recommend you to take a look at the slideshow tutorial on how to load an image, the rest should then be a piece of cake ;)

  57. Lynne Says:

    Thanks so much for this tutorial. It really helped me out. Whew!

  58. Younus Says:

    @Rafeal - Thanks for this tutorial!
    I have a general question, how can i use flv from XML file.

    Thanks

  59. Rafael Nünlist Says:

    @Lynne: Glad it could help you out ;)
    @Younus: Take a look at the “Expanding the Videoplayer” Tutorial, it implements a playlist function with xml.

  60. Ross Says:

    Fantastic tutorial and example! I was able to create a great dynamic streaming player using FMS 3.5 and Flash 10 using several examples from your code! Thank you!

  61. Nick Says:

    This tutorial is awesome!! thanks you for covering so much. This may seem simple but I’ve been having trouble. How do I get this player to play SWF’s instead of FLV’s?

  62. junebug Says:

    I expanded the width of the player to 640
    I moved the progress bar down to the middle part of the control bar… I have shortened the progress bar but when play is clicked the scrubber jumps all the way over to the left (Its 60px off) leaving a gap between the scrubber and progress bar… I know the problem is math related but I have played with code for 2 days and still cant get the scrubber to match back up with progress bar… in other words I have: 1.) dropped the scrubber down by 19 px
    2.) I have shortened the over all length of the scrubber/progress bar to 360px
    3.) slid the scrubber over to the right by 60 px

    problem is that when video starts, scrubber jumps all the way back over to the left… when the video is scrubbed the scrubber will then line up… but only when scrubbed

    the code that I need help with:
    ———————————
    function updateDisplay(e:TimerEvent):void {
    // checks, if user is scrubbing. if so, seek in the video
    // if not, just update the position of the scrubber according
    // to the current time
    if(bolProgressScrub)
    nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 354))
    else
    mcVideoControls.mcProgressScrubber.x = nsStream.time * 354 / objInfo.duration;

    // set time and duration label
    mcVideoControls.lblTimeDuration.htmlText = “” + formatTime(nsStream.time) + ” / ” + formatTime(objInfo.duration);

    // update the width from the progress bar. the grey one displays
    // the loading progress
    mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x + 5;
    mcVideoControls.mcProgressFill.mcFillGrey.width = nsStream.bytesLoaded * 360 / nsStream.bytesTotal;

  63. junebug Says:

    I moved the scrubber/progress bar down by 19 px.
    I moved the scrubber/progress bar over to the right by 60 px.

    I managed to get the scrubber to line up with the video progress bar after a little manipulation but now I have problems scrubbing.. trying to scrub results in the video jumping to the end…
    current code:

    function updateDisplay(e:TimerEvent):void {
    // checks, if user is scrubbing. if so, seek in the video
    // if not, just update the position of the scrubber according
    // to the current time
    if(bolProgressScrub)
    nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 354 + 60 ))
    else
    mcVideoControls.mcProgressScrubber.x = nsStream.time * 354 / objInfo.duration + 60;

    // set time and duration label
    mcVideoControls.lblTimeDuration.htmlText = “” + formatTime(nsStream.time) + ” / ” + formatTime(objInfo.duration);

    // update the width from the progress bar. the grey one displays
    // the loading progress
    mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x - 60;
    mcVideoControls.mcProgressFill.mcFillGrey.width = nsStream.bytesLoaded * 360 / nsStream.bytesTotal;

  64. khalil3 Says:

    Thank you sooooo much for your fantastic tool, I been searching for an AS3 tool for FLV, and I found it. ;)

  65. Rahul Joshi Says:

    I am working on the video player you have posted on your site. I have modified the XML and added another entry for sponsor video in it. If a particular entry in the XML has a sponsor video, it should be played first, then the video in that tag and so on. I am checking through actionscript if a sponsor video is present, then play it else just the normal video. Can you please guide me on how I can achieve this successfully?

  66. Agustin Says:

    I managed to install your player in FMS 3.5 on Windows 2003.
    Changed coding as explained above regarding function netStatusHandler etc.. Now i am getting the following error
    1120: Access of undefined property stopClicked
    lines 52 to 66 . What I am missing? I feel to be close to have this awesome player install.

  67. Nathan Says:

    This is great - many thanks. I had one question which I was wondering if you could help me with:

    Since Flash will now play MOV files (not just FLV files) is it possible to create a preview image dynamically? For example, load the Nth frame from the movie somehow, and have that appear as a static image before the movie is played?

    Or would it make more sense to merely pause the movie on the 1st frame, creating the illusion of a preview image?

  68. Carlos Pinho Says:

    I think you need Flash Media Server for that.

  69. Agustin Says:

    Hello: This is the code as modified so far. I still getting an error.
    Your player is excellent, but want to used in my website using FMS 3.5
    Can you help me?

    ERROR is:

    TypeError: Error #2007: Parameter connection must be non-null.
    at flash.net::NetStream/construct()
    at flash.net::NetStream()
    at videoplayer_fla::MainTimeline/frame1()

    ===============================================================

    // ##########################
    // ############# CONSTANTS
    // ##########################

    // time to buffer for the video in sec.
    const BUFFER_TIME:Number = 8;
    // start volume when initializing player
    const DEFAULT_VOLUME:Number = 0.6;
    // update delay in milliseconds.
    const DISPLAY_TIMER_UPDATE_DELAY:int = 10;
    // smoothing for video. may slow down old computers
    const SMOOTHING:Boolean = true;

    // ##########################
    // ############# VARIABLES
    // ##########################

    // flag for knowing if flv has been loaded
    var bolLoaded:Boolean = false;
    // flag for volume scrubbing
    var bolVolumeScrub:Boolean = false;
    // flag for progress scrubbing
    var bolProgressScrub:Boolean = false;
    // holds the last used volume, but never 0
    var intLastVolume:Number = DEFAULT_VOLUME;
    // net connection object for net stream
    var ncConnection:NetConnection;
    // net stream object
    var nsStream:NetStream;
    // object holds all meta data
    var objInfo:Object =”rtmp://XX.XX.XXX.XX/maximo2/”;
    // url to flv file
    var strSource:String = “hancock-tsr2_h480p.flv”;
    // timer for updating player (progress, volume…)
    var tmrDisplay:Timer;

    // ##########################
    // ############# FUNCTIONS
    // ##########################

    // sets up the player
    function initVideoPlayer():void {
    // hide buttons
    mcVideoControls.btnUnmute.visible = false;
    mcVideoControls.btnPause.visible = false;

    // set the progress/preload fill width to 1
    mcVideoControls.mcProgressFill.mcFillRed.width = 1;
    mcVideoControls.mcProgressFill.mcFillGrey.width = 1;

    // add global event listener when mouse is released
    stage.addEventListener( MouseEvent.MOUSE_UP, mouseReleased);

    // add event listeners to all buttons
    mcVideoControls.btnPause.addEventListener(MouseEvent.CLICK, pauseClicked);
    mcVideoControls.btnPlay.addEventListener(MouseEvent.CLICK, playClicked);
    mcVideoControls.btnStop.addEventListener(MouseEvent.CLICK, stopClicked);
    mcVideoControls.btnMute.addEventListener(MouseEvent.CLICK, muteClicked);
    mcVideoControls.btnUnmute.addEventListener(MouseEvent.CLICK, unmuteClicked);
    mcVideoControls.mcVolumeScrubber.btnVolumeScrubber.addEventListener(MouseEvent.MOUSE_DOWN, volumeScrubberClicked);
    mcVideoControls.mcProgressScrubber.btnProgressScrubber.addEventListener(MouseEvent.MOUSE_DOWN, progressScrubberClicked);

    // create timer for updating all visual parts of player and add
    // event listener
    tmrDisplay = new Timer(DISPLAY_TIMER_UPDATE_DELAY);
    tmrDisplay.addEventListener(TimerEvent.TIMER, updateDisplay);

    // create a new net connection, add event listener and connect
    // to null because we don’t have a media server
    ncConnection = new NetConnection();
    ncConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    ncConnection.connect(”rtmp://AA.214.65.40/maximo2/”);I HAVE HERE THE COMPLETE PATH
    }
    function netStatusHandler(event:NetStatusEvent):void {
    // handles net status events
    switch (event.info.code) {
    // trace a messeage when the stream is not found
    case “NetStream.Play.StreamNotFound”:
    trace(”Stream not found: ” + strSource);
    break;

    // when the video reaches its end, we stop the player
    case “NetStream.Play.Stop”:
    stopVideoPlayer();
    break;
    case “NetConnection.Connect.Success”:
    }
    }
    // create a new netstream with the net connection, add event
    // listener, set client to this for handling meta data and
    // set the buffer time to the value from the constant
    nsStream = new NetStream(ncConnection);
    nsStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nsStream.client = this;
    nsStream.bufferTime = BUFFER_TIME;

    // attach net stream to video object on the stage
    vidDisplay.attachNetStream(nsStream);
    // set the smoothing value from the constant
    vidDisplay.smoothing = SMOOTHING;

    // set default volume
    mcVideoControls.mcVolumeScrubber.x = (52 * DEFAULT_VOLUME) + 341;
    mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 52;
    setVolume(DEFAULT_VOLUME);

    function playClicked(e:MouseEvent):void {
    // check’s, if the flv has already begun
    // to download. if so, resume playback, else
    // load the file
    if(!bolLoaded) {
    nsStream.play(strSource);
    bolLoaded = true;
    }
    else{
    nsStream.resume();
    }

    // show video display
    vidDisplay.visible = true;

    // switch play/pause visibility
    mcVideoControls.btnPause.visible = true;
    mcVideoControls.btnPlay.visible = false;
    }

    function pauseClicked(e:MouseEvent):void {
    // pause video
    nsStream.pause();

    // switch play/pause visibility
    mcVideoControls.btnPause.visible = false;
    mcVideoControls.btnPlay.visible = true;
    }

    function stopClicked(e:MouseEvent):void {
    // calls stop function
    stopVideoPlayer();
    }

    function muteClicked(e:MouseEvent):void {
    // set volume to 0
    setVolume(0);

    // update scrubber and fill position/width
    mcVideoControls.mcVolumeScrubber.x = 341;
    mcVideoControls.mcVolumeFill.mcFillRed.width = 1;
    }

    function unmuteClicked(e:MouseEvent):void {
    // set volume to last used value
    setVolume(intLastVolume);

    // update scrubber and fill position/width
    mcVideoControls.mcVolumeScrubber.x = (53 * intLastVolume) + 341;
    mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;
    }

    function volumeScrubberClicked(e:MouseEvent):void {
    // set volume scrub flag to true
    bolVolumeScrub = true;

    // start drag
    mcVideoControls.mcVolumeScrubber.startDrag(false, new Rectangle(341, 19, 53, 0));
    }

    function progressScrubberClicked(e:MouseEvent):void {
    // set progress scrub flag to true
    bolProgressScrub = true;

    // start drag
    mcVideoControls.mcProgressScrubber.startDrag(false, new Rectangle(0, 2, 432, 0));
    }

    function mouseReleased(e:MouseEvent):void {
    // set progress/volume scrub to false
    bolVolumeScrub = false;
    bolProgressScrub = false;

    // stop all dragging actions
    mcVideoControls.mcProgressScrubber.stopDrag();
    mcVideoControls.mcVolumeScrubber.stopDrag();

    // update progress/volume fill
    mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x + 5;
    mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;

    // save the volume if it’s greater than zero
    if((mcVideoControls.mcVolumeScrubber.x - 341) / 53 > 0)
    intLastVolume = (mcVideoControls.mcVolumeScrubber.x - 341) / 53;
    }

    function updateDisplay(e:TimerEvent):void {
    // checks, if user is scrubbing. if so, seek in the video
    // if not, just update the position of the scrubber according
    // to the current time
    if(bolProgressScrub)
    nsStream.seek(Math.round(mcVideoControls.mcProgressScrubber.x * objInfo.duration / 432))
    else
    mcVideoControls.mcProgressScrubber.x = nsStream.time * 432 / objInfo.duration;

    // set time and duration label
    mcVideoControls.lblTimeDuration.htmlText = “” + formatTime(nsStream.time) + ” / ” + formatTime(objInfo.duration);

    // update the width from the progress bar. the grey one displays
    // the loading progress
    mcVideoControls.mcProgressFill.mcFillRed.width = mcVideoControls.mcProgressScrubber.x + 5;
    mcVideoControls.mcProgressFill.mcFillGrey.width = nsStream.bytesLoaded * 438 / nsStream.bytesTotal;

    // update volume and the red fill width when user is scrubbing
    if(bolVolumeScrub) {
    setVolume((mcVideoControls.mcVolumeScrubber.x - 341) / 53);
    mcVideoControls.mcVolumeFill.mcFillRed.width = mcVideoControls.mcVolumeScrubber.x - 394 + 53;
    }
    }

    function onMetaData(info:Object):void {
    // stores meta data in a object
    objInfo = info;

    // now we can start the timer because
    // we have all the neccesary data
    tmrDisplay.start();
    }

    function stopVideoPlayer():void {
    // pause netstream, set time position to zero
    nsStream.pause();
    nsStream.seek(0);

    // in order to clear the display, we need to
    // set the visibility to false since the clear
    // function has a bug
    vidDisplay.visible = false;

    // switch play/pause button visibility
    mcVideoControls.btnPause.visible = false;
    mcVideoControls.btnPlay.visible = true;
    }

    function setVolume(intVolume:Number = 0):void {
    // create soundtransform object with the volume from
    // the parameter
    var sndTransform = new SoundTransform(intVolume);
    // assign object to netstream sound transform object
    nsStream.soundTransform = sndTransform;

    // hides/shows mute and unmute button according to the
    // volume
    if(intVolume > 0) {
    mcVideoControls.btnMute.visible = true;
    mcVideoControls.btnUnmute.visible = false;
    } else {
    mcVideoControls.btnMute.visible = false;
    mcVideoControls.btnUnmute.visible = true;
    }
    }

    function formatTime(t:int):String {
    // returns the minutes and seconds with leading zeros
    // for example: 70 returns 01:10
    var s:int = Math.round(t);
    var m:int = 0;
    if (s > 0) {
    while (s > 59) {
    m++;
    s -= 60;
    }
    return String((m < 10 ? “0″ : “”) + m + “:” + (s < 10 ? “0″ : “”) + s);
    } else {
    return “00:00″;
    }
    }

    // ##########################
    // ############# INIT PLAYER
    // ##########################
    initVideoPlayer();

  70. agustin Says:

    I am able to connect to my FMS3 but .flv doesnt play. I go online: see all buttons, play, stop, scroll they seem to work, but not luck.
    I opened all the appropriate ports. If I connect, what could be the cause of no video play.

    Thank you

  71. Rafael Nünlist Says:

    @Ross: Cool, nice to hear that!

    @Nick: If you want to have a player that controls timeline animations, then you should take a look @ the beta of TweenMax 11 which will support that kind of stuff ;) ( http://blog.greensock.com/v11beta/ )

    @khalil3: Glad we could help you out :)

    @Rahul Joshi: Could you explain your problem a little bit more in detail? Should the videoplayer disable the functionalities when playing a advertising? Otherwise you could just stick to the expanded video player posted on the techlabs.

    @All issues with FMS: There will be a new videoplayer tutorial on how to connect to a liveserver since this is a little bit different from progressive streaming.
    For a preview image you could either use a serverside script like php ffmpeg ( http://ffmpeg-php.sourceforge.net/ ) and make a snapshot from the video or you just upload the preview image directly on your webserver and load it.

  72. Rahul Joshi Says:

    I have posted the questions in the expanded video player post.

  73. Michael Says:

    Thanks for the tutorial Rafael. I’m new to Flash and this has helped me learn a lot.

    I’m trying to make the player be able to play multiple videos. I have made buttons that call each video. I have put the entire player and it’s actions into a movieclip and named the movieclip “flvPlayer.” In the “Variables” section I have removed the = “hancock-tsr2_h480p.flv” so now it just says var strSource:String;

    Then in the main timeline, which contains all the buttons, I have a frame with actions. The first action is for the video to play a video:

    flvPlayer.strSource = “AuditoriumImage.flv”;

    Then each button has a code that looks like this:

    function video1(event:MouseEvent):void {
    flvPlayer.strSource = “Video1.flv”;
    }
    video1Button.addEventListener(MouseEvent.CLICK,video1);

    The first video plays perfectly, but then none of the other videos will play. I’m sure it is a simple fix. Can anyone help me out?

  74. Greg Says:

    To the author of this tutorial,

    I am also working on a custom flash player. I have run into a problem with the buffer:

    After the video is paused (stream.pause) if I wait for 10 seconds or so… then resume video (stream.resume)… the video starts to play very fast, almost like fast forward — seems like it’s been buffering while it was paused and once it is resumed it is trying to catch up with it — which it shouldn’t, it should just continue playing at the normal rate. Once the video catches up with the amount of time you’ve waited while in pause, it continues to play at normal speed.

    Have you run into this problem before? I would like to know your thoughts about this.

  75. Flash Nut Says:

    This is an awesome tutorial, I love it. The only thing I’m having problems with is resizing. I’m trying to make the video player smaller and I’m running into a few issues with doing so (mainly with the scrubbers and the fills). So what I’m trying to do is make things a little easier to work with by removing the hard coded numbers, and putting in the corresponding variables so hopefully when i shrink things, the scrubbers will stay consistent with the fill area.

    With that said, toward the end of the initVideoPlayer(); function, there are some numbers there 394, and 52, can you tell me what those numbers represent?

  76. anonymous Says:

    Great tutorial!

    If I were you I’d mention my name at the top of the code. I don’t like to reinvent hot water, so I will often use code I find on the internet, I don’t like to take credit for this work though, so I keep the name of the author in it

    Also, a lot of your size variables are hard coded, if these were flexible the player would be even better and easier to modify for further projects.

  77. Ramin Says:

    Hello.
    I’ve got this excellent player to work, but there are some issues that I don’t know how to fix.

    I need to put 3 players on one page. What I need is to stop all movies and sounds (if playing) before the selected movie is start playing.

    Is there anyway to do this?

    PS. I would also love it if I could mute the background music on the site as well.

  78. James Says:

    Hi Rafael,

    Great tutorial, this saved me a great deal of research.

    I have taken the player and adapted it to my needs but it has suddenly started acting strangely and I cant figure out why.

    The problem is that once it buffers it skips through the video too fast until it reaches the buffer point, after which it runs smoothly.

    The site can be found at http://jelly.ndltec.com

    Any ideas would be greatly appreciated.

    Thank you very much!

    James

  79. James Says:

    Oh, i forgot to say. the player is at:

    work - visual effects - pet dinosaur

    Thanks again in advance for any help!

  80. BJ Says:

    how can i make this player to when loading finished video starts playing.
    i’m using this player for my friends website.

  81. amar Says:

    tip: If you want the controls & the video to react to mouse over/out you can put an invisible layer in the mcVideoControl of the size of the video…

    plz,explain in detail thank’s in advance

  82. amar Says:

    tip: If you want the controls & the video to react to mouse over/out you can put an invisible layer in the mcVideoControl of the size of the video…

    plz,explain in detail thank’s in advance

    i do all the possible try so plz plz plz ans me

  83. fogpuddle Says:

    Hello,

    I’m just getting my hands dirty with AS3.0 and think this video player script is awesome!! I’ve played with it and customized just about all the script to work with a video skin I created. However, I’m having one issue that I can’t figure out. I noticed in the skin you provided, the Progress Scrubber starts at X position 0 when I push the play button. However, for the skin I’m building, I want the Progress Scrubber start at X position 22 when I hit the Play button, but I can’t get it to happen that way! It keeps starting at X position 0 and I looked throughout the whole script trying to find where I need to make the change. I’m having no luck. Can you help? Again, this is happening after I click on the Play button. Thanks.

  84. James Says:

    Hi fogpuddle, I would just turn each player section into a new MovieClips so you can move them around at your leisure. If you do this you will then have to go through each bit of code that references those bits, ie:

    playerScrubber.x = 3;

    and change the path so it becomes:

    newMovieClip.playerScrubber.x = 3.

    If you do this for all of them then it will be much easier to change around.

    Good luck!

  85. Beauceron Says:

    Thanks for the tuto it work #1 on local but when i put it on my server the video doesn’t work i check 4 times the URL and they are right but it doesn’t work!!

    i made a variable for the URL and it takes is information directly from my main swf like that :
    var urlVariable:String = this.parent.parent.parent["videoUrl"];

    i suppose this is my variable the problem but can you help me pls?

  86. fogpuddle Says:

    Thanks James for the help. After rearranging the code and numbers when creating the additional movie clips, I prefer this method over the original due to it’s flexibility. That little tidbit was all I needed to get things working. 8)

8 Trackbacks For This Post

  1. Tutorials | The Tech Labs Roundup « Flash Enabled Blog Says:

    [...] How to build a AS3 Videoplayer [...]

  2. AS3 Video Player tutorials roundup | Lemlinh.com Says:

    [...] Read more [...]

  3. Link Post Sunday 08/24 | Mr Sun Studios Says:

    [...] How to Build an AS3 Videoplayer by The Tech Labs [...]

  4. Ramblings › Just another WordPress weblog Says:

    [...] How to build a AS3 Videoplayer | The Tech Labs (tags: flash actionscript tutorial) [...]

  5. Ultimate List Of 40 Quality Flash Tutorials For Your Animated Desire | The Theme Blog Says:

    [...] How To Build An AS3 Videoplayer [...]

  6. Flash Video - Year of the Ape Says:

    [...] > How to build a Flash AS3 Videoplayer: http://www.thetechlabs.com/video/how-to-build-a-as3-videoplayer/ [...]

  7. Flash Actionscript 3 URL link button | Alex Brooke Says:

    [...] The video player I used for this example was made by Rafael Nuenlist. You can view the tutorial here. [...]

  8. Daily Digest - Inspiration & Resources 19 June 09 » De Web Times - Sharing Useful Resources. Says:

    [...] How to build a Flash Actionscript 3.0 Videoplayer [...]

Leave a Reply