Streaming Video
This section will bring together all the steps we have gone over so far into a media streaming application.The first step is to either create your own Flash Video using the steps we went over earlier or download the one from the companion website.When you have the Flash video, follow these steps to build a simple video streaming application:
This code accomplishes several things; let's break it into sections so that it can be more easily analyzed.The first section creates a NetConnection object and then calls the connect() method to make a local connection:
The next section creates the NetStream object and sets its onStatus event to send what caused the event to the text field we created.
//Create the NetConnection object:
var myConn_nc:NetConnection = new NetConnection();
//Create the connection
myConn_nc.connect(null);
The next section attaches the NetStream video to the video object. Then it sets the buffer time (but because we are running locally, it really doesn't matter). Finally, it creates a variable we will use to see whether the video has started streaming yet.
//Create the NetStream object
var myStream_ns:NetStream = new NetStream(myConn_nc);
//Set the onStatus event for the NetStream object
myStream_ns.onStatus = function(infoObject){
status_txt.text=infoObject.code;
}
In the final section, we create a listener to listen to the Play button component. We create the event for the listener that checks to see whether the user has started streaming the video yet. If the video has not started streaming yet, it will start; set the variable to true so that it won't try to start it again, and set the label for the Play button to "Pause" so that the user will know it is playing. After that, if the user clicks the button again, it checks the label to see what the user is trying to do, and it either plays or pauses the movie accordingly. Finally, we add the event listener to the Button component.
//Attach the NetStream video to the Video object
myVideo_video.attachVideo(myStream_ns);
//Set the buffer time to 5 seconds
myStream_ns.setBufferTime(5);
//create a variable to see if we have played the video yet
var played:Boolean = false;
Test the movie and click the Play button; you will see something similar to Figure 26.4. You can then pause and resume play, and the text field shows you when the onStatus event fires.
//create an object to listen to our play button
var clickListen:Object = new Object();
//create the event for the listener
clickListen.click = function(){
if(!played){
myStream_ns.play("cats.flv");
played = true;
play_butn.label = "Pause";
}else{
if(play_butn.label == "Play"){
play_butn.label = "Pause";
}else{
play_butn.label = "Play";
}
myStream_ns.pause();
}
}
//now add the listener to the button
play_butn.addEventListener("click", clickListen);
Figure 26.4. Streaming video is a snap with the NetStream and NetConnection objects.
