BUY THIS BOOK
Add to Cart

PDF $19.99

Safari Books Online

What is this?

Looking to Reprint or License this content?


Learning Flash Media Server 3
Learning Flash Media Server 3 By William B. Sanders

Cover | Table of Contents


Table of Contents

Chapter 1: Getting Started with Flash Media Server 3
The release of Flash Media Server 3 (FMS3) comes in three different server configurations. First is Flash Media Interactive Server 3 (FMIS3), with full features for interactive streaming, and incorporating features of the previous Origin and Edge editions. Similar to the full Flash Media Server 2 version, FMIS3 has more features: This new edition does not restrict the number of concurrent connections or bandwidth usage.
The second version of FMS3 is the Flash Media Streaming Server 3 (FMSS3). This server is limited to streaming video and audio. Think of it as similar to progressive downloading, except FMSS3 uses server streaming. If your main goal is to stream audio and video from a site, this option provides a much lower cost server than FMIS3, with no limits on concurrent users or bandwidth. Using the Flash Media Encoder 2, you can use FMSS3 for live video streaming of either H.264 or On2 VP6 video.
The third version of FMS3 is the free Flash Media Development Server 3 (FMDS3). With the same features as the FMIS3 server, this version is limited to 10 concurrent users and cannot be used in a production environment. You can use it to develop applications that will run either on your own computer or a local area network (LAN), for either the FMIS3 or FMSS3 servers.
To avoid confusion, this book refers to all three versions simply as FMS3. You will need to keep in mind that the FMSS3 server cannot be used for recording video or interactive chats, and has other limitations. However, using the Development version of the server, you can create and test all of the examples in this book. You can even record your own FLV video files and play them on either of the other two servers.
If you’ve used Flash Communication Server or Flash Media Server 2 and understand its use, you can skip this section. Flash Media Server 3 is the latest version of Flash Media Server and has several improvements. However, if you’re new to working with open socket technology, including FMS3, read on.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The New Flavors for Flash Media Server 3
The release of Flash Media Server 3 (FMS3) comes in three different server configurations. First is Flash Media Interactive Server 3 (FMIS3), with full features for interactive streaming, and incorporating features of the previous Origin and Edge editions. Similar to the full Flash Media Server 2 version, FMIS3 has more features: This new edition does not restrict the number of concurrent connections or bandwidth usage.
The second version of FMS3 is the Flash Media Streaming Server 3 (FMSS3). This server is limited to streaming video and audio. Think of it as similar to progressive downloading, except FMSS3 uses server streaming. If your main goal is to stream audio and video from a site, this option provides a much lower cost server than FMIS3, with no limits on concurrent users or bandwidth. Using the Flash Media Encoder 2, you can use FMSS3 for live video streaming of either H.264 or On2 VP6 video.
The third version of FMS3 is the free Flash Media Development Server 3 (FMDS3). With the same features as the FMIS3 server, this version is limited to 10 concurrent users and cannot be used in a production environment. You can use it to develop applications that will run either on your own computer or a local area network (LAN), for either the FMIS3 or FMSS3 servers.
To avoid confusion, this book refers to all three versions simply as FMS3. You will need to keep in mind that the FMSS3 server cannot be used for recording video or interactive chats, and has other limitations. However, using the Development version of the server, you can create and test all of the examples in this book. You can even record your own FLV video files and play them on either of the other two servers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is a Media Server?
If you’ve used Flash Communication Server or Flash Media Server 2 and understand its use, you can skip this section. Flash Media Server 3 is the latest version of Flash Media Server and has several improvements. However, if you’re new to working with open socket technology, including FMS3, read on.
FMS3 is an open socket server. The key difference between open socket servers and Web servers is that as soon as you receive information from a Web server, the connection is broken. It may look as if you’re still connected to the Web server, especially with a Flash page that’s animating materials. However, that’s not the way it works. If you open a Web page, the Web server sends you the page along with all associated graphics, text, and other media; and your computer sends a message back that says, “Got it!” (or something to that effect), and the connection closes. With an open socket server, the connection stays open until you quit the application or trigger an event that cuts the connection. Because the connection remains open, you can stream audio, video, text, and any other media available on the Internet, in real time. You just can’t do that with a regular Web server because it has an entirely different architecture.
When you use a regular Web page, you’re most likely using HTTP (Hypertext Transfer Protocol), which allows you to look at Web pages. To be able to work with streaming media, Adobe developed Real-Time Messaging Protocol (RTMP). Generally, when you use FMS3, you first connect to a Web server via HTTP and then to Flash Media Server using RTMP. Because of this arrangement, you’re working simultaneously with different protocols—one for the Web site and the other for the streaming media.
To deal with all the things you can do with FMS3, you have two additional language Application Program Interfaces (APIs). Both APIs are extensions of ActionScript and are called Client-Side Media ActionScript and Server-Side Media ActionScript, or in this book, simply
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing FMS3
You can install FMS3 on either a Windows or Linux OS. For a Windows server, you need at least Windows 2000, which means you can install it on your Windows Home, XP, or Vista edition. If you’re installing it on your company’s server, you’ll probably be using Windows 2003 Standard Edition, Windows 2005 Server, or the new Windows 2008 Server. For your Linux box, either Red Hat Enterprise version 3 or 4 will do the trick. You’ll need a 3.2 GHz or faster Pentium 4 (or some other X86-compatible processor), 1 GB of RAM, and 50 MB of hard drive space. For this book, I used a 3 GHz Pentium 4 with 1 GB of RAM running on Windows XP, Windows Vista on another server, and Red Hat version 4 on a Linux server.
You cannot install FMS3 on Mac OS or Apple OS server. However, you can develop FMS3 applications on a Macintosh and install FMS3 on the “MacTel” version of a Macintosh running Windows. If you run both Windows and Mac OS X at the same time on your Macintosh—using Parallels—you can run the Flash application on the Macintosh side and FMS on the PC side. Also, you can install FMS3 on a Linux server, but you cannot develop applications on a Linux machine. (Adobe doesn’t make a Linux version of Flash.) This apparent paradox recognizes that the two main server technologies are Windows and Linux, and the two main development platforms are Windows and Macintosh.
As you will soon see, this doesn’t mean that you cannot develop and test FMS3 apps on your Macintosh. Rather, it means that you’ll just have to install FMS3 on a remote server (which would include your Windows computer sitting on the same desktop or even in your lap). The big advantage of running your application on one computer and FMS3 on another is that your processor doesn’t have to concentrate on two things at once. So if you’ve got a Macintosh, don’t worry. Most of the applications developed for this book were done using a Macintosh with the FMS3 server connected via a LAN to a PC running Windows XP. Of course, if you have a newer Macintosh with the Intel processor, you can run them both on the same machine, as long as Mac OS and Windows OS are running in parallel.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Organizing Your Development Environment
If you follow the default installation, your Flash Media Server 3 should start up every time you turn on your computer. Within this environment you need to set up your work environment so that you can conveniently test your applications.
When you install FMS3 on Windows, your typical installation is going to set up your server-side files with the following path:
          C:\Program Files\Adobe \Flash Media Server 3\applications
        
All of your server-side application folders go into the folder named applications. For example, shows a visual view of the paths with three applications in the applications folder named ideafactory, flvedit, and textChat. The application folders must be named with the application name. That is, if your application is named “vidChat”, you must name the folder “vidChat.” The folder can be empty or contain other files. If you have written server-side code for your application, the file must be named main.asc or the same name as your application, such as vidChat.asc. Throughout this book I use the same name as the applications for the ASC files to reduce confusion when discussing more than one application with server-side code.
Figure : Path to server-side applications
In , the ideafactory and flvedit applications contain ASC files with the same name as the application folder, and the textChat application’s ASC file is named mainASC, but it could have been named textChat.asc. Likewise, all of the others ASC files could have been named main.asc. Use whatever system is convenient for you. As you look at different applications in this book, you’ll see different folders associated with server-side files.
Your client-side files are the Flash FLA, AS, and SWF files that you’re used to working with in Flash. If you have your server on your computer, they can go anywhere. When you use the Control Test Movie sequence with your application, your server will be found and everything should work fine. However, if you want to test your applications using a LAN or just using your browser, you need to place them where they will be recognized by your Web server using the HTTP protocol on your localhost (127.0.0.1) or local LAN IP address. That is, all your HTML and SWF files need to be placed in the Web server’s root directory. Because it’s easier to develop and test applications, you also can place the FLA and AS files in the same folders as the SWF and HTML files. shows a typical setup on a Windows XP box using an Apache Web server.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing FMS3 Connections
The protocol to connect to Flash Media Server 3 is RTMP—Real-Time Messaging Protocol. The newest version of RTMP is RTMPE (E for Encryption). The examples show both. The older RTMP is a bit faster, but RTMPE performs better for encryption and is more secure. You set up a net connection, and then place the RTMP path in your NetConnection instance. The basic routine is as follows:
nc = new NetConnection( );
nc.connect("rtmp:/appName");
If your path is to a server on the same computer (or physical server) as your application, you use only a single “/” slash; however, if your path is to a remote server or LAN, you use a double slash “//” as follows:

Same computer:

nc.connect("rtmp:/FMSapp")

Different computers:

nc.connect("rtmp://www.myDomain.com/FMSapp")
Since I develop on a LAN, I used the latter. Also, I like to put the RTMP string into a string variable. Then when I have to change RTMP paths, I just comment out the old string and remove comment slashes from what I want to use. The examples in this book use the single slash, but the LAN version is commented out. Also, if you use a LAN, make sure that your RTMP uses the IP address for the FMS3 server location, and not the IP address where your client-side materials are being developed.
Once you’ve got your folder arrangements set up, you need to make a connection to test whether your FMS3 is performing in conjunction with your applications. To do this, you need a simple FMS3 application to test. If you don’t have Flash installed, download the latest version from the Adobe.com Web site and install it. You will need the Flash IDE to follow the examples in this book. The following steps show you how to create a simple FMS3 application to test:
  1. Open a new Flash file (ActionScript 3.0); this is an FLA file. Save it as FMS3Connect.fla.
  2. Add a logo to the upper left corner of the Stage. (Optional).
  3. Open the Property inspector from the Window menu. In the Document Class text box, type
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the FMS3 Administration Console
To see what’s going on in your server, you need to use the FMS3 Administration console. It shows you what’s going on behind the scenes on your media server. If your FMS3 is on Windows, navigate to Start All Programs Adobe Flash Media Server 3 Management Console, as shown in .
When you initially open the Administration console, you will be asked to enter the Administrative user name and password. This is the name and password you wrote down when you installed your server. (See .) Type your user name and password, and if your server is in a secure location, you can click the check boxes to remember the information and automatically open the console when you start it. For development, I use the Administration console all the time, so I have the user name and password automatically entered. However, if your development environment is not secure, you should require that the user enter the user name and password.
Launch the application FMS3Connect, developed in the previous section. In the Administration console, select the ViewApplications Clients option. When the application successfully launches, you will see the name of the application, the number of clients currently using the application, plus other information about the client as shown in .
Figure : Flash Media Administration Console
As you become more familiar with FMS3, you will find the Administration console more useful. In subsequent chapters, you’ll see how it can provide invaluable feedback on what your server is doing.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using This Book
Learning with Flash Media Server 3 is designed to offer you options, but at the heart of every chapter is a core set of code that shows the minimum requirements needed for different procedures. Later chapters will have some material that is more complex, more sophisticated, and optimized for getting the most out of FMS3. The chapters will include the minimalist set of code for different operations. This code is presented as a procedure with the sole purpose of clarifying what must be in place for something to happen. It won’t be sophisticated, but it will work and help you understand how to accomplish different goals with FMS3. In the more advanced chapters, the same operations may be rendered as a class or even a component. Sometimes in the same chapter you will see a range of solutions for the same task, ranging from a simple procedure to an object-oriented class to a design pattern.
Unlike previous versions of Flash Media Server, FMS3 arrives with the introduction of a major ActionScript revision. ActionScript 3.0 is the first true ECMAScript 4 implementation of ActionScript. In the future, expect more languages to adopt one ECMA standard or another. As Internet languages adopt these standards, different languages will overlap more and require less work to learn a new one. Because ActionScript 3.0 represents a very different way of programming in ActionScript—more like Java, C++ and C#—you may need to take some time to go over it. All of the client-side code is in ActionScript 3.0 and the server-side script is in ActionScript 1.0; so the server-side script may actually be more familiar to you. In fact, if you don’t know Flash and ActionScript, before you go too far with FMS3, you’d better spend some time getting up to speed on both. All of the examples in this book use Flash CS3 and ActionScript 3.0, which means that most of the code won’t work with earlier versions of Flash. However, if you are using Flex 2 or later, you should be able to work around some of the Flash CS3 elements and reproduce the examples.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Recording and Playing Back Streaming Audio and Video
Flash Media Server 3 can both record and play back streaming audio and video. The nature of streaming is not the same as broadcasting. In broadcasting, the sender sends out a single signal; everyone who connects to the channel sending the signal gets the same stream. It’s like dropping a pebble in the water—a concentric circle of waves sends out a “signal.” No matter where viewers or listeners are, when the wave reaches them, they get the same wave—like a TV picture or radio transmission—as everyone else.
When FMS3 sends out a stream of audio and video, it creates a separate stream for each recipient. Its “broadcasting” works more like the spokes on a wagon wheel, where everyone connected gets his or her own stream. So here the term “broadcasting,” really means a form of streamcasting—a technology where everyone gets a separate stream. If one person is listening, my application sends only a single stream; but if 20 people are listening, it generates 20 streams. Because the server automatically creates a separate stream for each user connected, you don’t have to create all those streams in your coding. However, in deciding how to set up your application, for bandwidth considerations you need to consider the number of streams it may generate.
If you’ve ever viewed online video, you’ve probably seen different kinds without really realizing it. If you click on a video and have to wait a long time, what you’re really waiting for is for the video file to first download and then for your computer to play the video that’s saved to your hard drive. That works fine except you have to wait until the file is fully downloaded before you can watch it. Also, it’s saved on your hard drive taking up space. A second type of video processing is called progressive download. It’s like a hybrid of a video download and streaming. As the video file is downloaded, it begins to play rather than wait for the whole thing to download. However, the file will end up on the user’s hard drive, and processing is not as smooth as true streaming. The third type of video processing, if you have FMS3 on your server, lets you stream video files from the server. This chapter explains how to get started with both creating and streaming Flash Video (FLV) files using FMS3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Streaming and Broadcasting
Flash Media Server 3 can both record and play back streaming audio and video. The nature of streaming is not the same as broadcasting. In broadcasting, the sender sends out a single signal; everyone who connects to the channel sending the signal gets the same stream. It’s like dropping a pebble in the water—a concentric circle of waves sends out a “signal.” No matter where viewers or listeners are, when the wave reaches them, they get the same wave—like a TV picture or radio transmission—as everyone else.
When FMS3 sends out a stream of audio and video, it creates a separate stream for each recipient. Its “broadcasting” works more like the spokes on a wagon wheel, where everyone connected gets his or her own stream. So here the term “broadcasting,” really means a form of streamcasting—a technology where everyone gets a separate stream. If one person is listening, my application sends only a single stream; but if 20 people are listening, it generates 20 streams. Because the server automatically creates a separate stream for each user connected, you don’t have to create all those streams in your coding. However, in deciding how to set up your application, for bandwidth considerations you need to consider the number of streams it may generate.
If you’ve ever viewed online video, you’ve probably seen different kinds without really realizing it. If you click on a video and have to wait a long time, what you’re really waiting for is for the video file to first download and then for your computer to play the video that’s saved to your hard drive. That works fine except you have to wait until the file is fully downloaded before you can watch it. Also, it’s saved on your hard drive taking up space. A second type of video processing is called progressive download. It’s like a hybrid of a video download and streaming. As the video file is downloaded, it begins to play rather than wait for the whole thing to download. However, the file will end up on the user’s hard drive, and processing is not as smooth as true streaming. The third type of video processing, if you have FMS3 on your server, lets you stream video files from the server. This chapter explains how to get started with both creating and streaming Flash Video (FLV) files using FMS3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Minimalist Project
To get started you’ll create a little project containing the minimum number of elements needed to create an FLV file using ActionScript 3.0. The following are the packages and classes you’ll need (client-side):
Packages
fl.controls.Button;
fl.controls.TextInput;
flash.display.Sprite;
flash.net.NetConnection;
flash.net.NetStream;
flash.events.NetStatusEvent;
flash.events.MouseEvent;
flash.events.Event;
flash.net.ObjectEncoding;
flash.media.Camera;
flash.media.Microphone;
flash.media.Video;
Key Classes
NetConnection
NetStream
Camera
Microphone
Video
Button
The package list shows all the packages you will need for the final application in this chapter that both records and plays back FLV files using FMS3. Of these packages, one of the most important to import is the ObjectEncoding package. FMS2 (in case you’re using it instead of FMS3) requires the NetConnection property defaultObjectEncoding to change the AMF default from 3 to 0 using the following line:
NetConnection.defaultObjectEncoding = flash.net.ObjectEncoding.AMF0;
You will see this property used throughout the book for FMS2 users who want to employ ActionScript 3.0 in their client-side code. Just uncomment the defaultObjectEncoding lines.
One more important chore before you get to the actual coding. You need a server-side folder named vid2. This will be your FMS application folder, and while it won’t need a server-side (ASC) file, it’s needed to run your FMS application. After you run your first application, you will find additional folders inside the vid2 folder.
To set up an application to record video, you will need a Webcam connected to your computer and a microphone. Some Webcams have built-in microphones, others have no microphones, and still others come with ones that must be plugged into the microphone port of your computer. Many computers come with built-in microphones, especially on portable computers and most versions of Macintosh computers. You also may find that a Webcam comes installed in your computer. Some Windows-based portable computers, and iMac and MacBook model Macintosh computers have built-in Webcams as well as microphones.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Combined Record and Playback Application
This final minimalist application can be used for both recording and playback. It uses two video windows so that you can keep the live view while reviewing a recorded video. Also, it uses the MovieClip object as a subclass instead of as a Sprite class in setting up the RecordPlay class. This change illustrates how you might incorporate a logo based on a MovieClip object in your application..
Follow these steps to develop the application:
  1. Create a new Flash file (ActionScript 3.0), set the Stage size in the Property inspector to 650 × 400 pixels. If you like, add a background color. Save the file as RecordPlay.fla
  2. Use your own logo or make one up on the Stage. (Just draw a simple logo, select it, press the F8 button, and select Movie Clip as Type, click Export for ActionScript, and click OK.)
  3. In the Property inspector in the Document Class text box, type RecordPlay and save the FLA file again.
  4. Next, open an ActionScript 3.0 file and save it as RecordPlay.as in the same folder as the RecordPlay.fla file.
  5. In the RecordPlay.as file, enter the code in and save the file again.
Example . RecordPlay.as
package
{
  import fl.controls.Button;
  import fl.controls.TextInput;
  import flash.display.MovieClip;
  import flash.net.NetConnection;
  import flash.net.NetStream;
  import flash.events.NetStatusEvent;
  import flash.events.MouseEvent;
  import flash.events.Event;
  //import flash.net.ObjectEncoding;
  import flash.media.Camera;
  import flash.media.Microphone;
  import flash.media.Video;

  public class RecordPlay extends MovieClip
  {
        private var nc:NetConnection;
        private var ns:NetStream;
        private var rtmpNow:String;
        private var msg:Boolean;
        private var cam:Camera;
        private var mic:Microphone;
        private var vid1:Video;
        private var vid2:Video;
        private var recordBtn:Button;
        private var stopBtn:Button;
        private var playBtn:Button;
        private var textInput:TextInput;
        private var metaSniffer:Object;
        private var dur:Number;

        function RecordPlay ()
        {
             //NetConnection.defaultObjectEncoding = flash.net.ObjectEncoding.AMF0;
             nc=new NetConnection();
             nc.addEventListener (NetStatusEvent.NET_STATUS,checkConnect);
             rtmpNow="rtmp://192.168.0.11/vid2/recordings";
             //rtmpNow="rtmp:/vid2/recordings";
             nc.connect (rtmpNow);
             addMedia ();
             addUI ();
             recordBtn.addEventListener (MouseEvent.CLICK,startRecord);
             stopBtn.addEventListener (MouseEvent.CLICK,stopAll);
             playBtn.addEventListener (MouseEvent.CLICK,startPlay);
        }

        private function checkConnect (e:NetStatusEvent):void
        {
             msg=(e.info.code=="NetConnection.Connect.Success");
             if (msg)
             {
                   ns = new NetStream(nc);
                   metaSniffer=new Object();
                   ns.client=metaSniffer;
                   metaSniffer.onMetaData=getMeta;
             }
        }

        private function getMeta (mdata:Object):void
        {
             //Dummy to avoid error
        }

        private function addMedia ():void
        {
             cam=Camera.getCamera();
             cam.setKeyFrameInterval (12);
             cam.setMode (240,180,15);
             cam.setQuality (0,80);
             mic=Microphone.getMicrophone();
             mic.rate=11;
             videoSetup ();
        }

        private function videoSetup ():void
        {
             vid1=new Video(cam.width,cam.height);
             vid1.attachCamera (cam);
             vid1.x=100;
             vid1.y=70;
             addChild (vid1);
             vid2=new Video(cam.width,cam.height);
             vid2.x=vid1.x+vid1.width+10;
             vid2.y=vid1.y;
             addChild (vid2);
        }

        private function addUI ():void
        {
             recordBtn=new Button();
             recordBtn.label="Record";
             recordBtn.x=100;
             recordBtn.y=70+(cam.height) +5;
             recordBtn.width=70;
             addChild (recordBtn);
             stopBtn=new Button();
             stopBtn.label="Stop";
             stopBtn.x=recordBtn.x+100;
             stopBtn.y=recordBtn.y;
             stopBtn.width=60;
             addChild (stopBtn);
             playBtn=new Button();
             playBtn.label="Play";
             playBtn.x=stopBtn.x+85;
             playBtn.y=recordBtn.y;
             playBtn.width=60;
             addChild (playBtn);
             textInput=new TextInput();
             textInput.x=recordBtn.x;
             textInput.y=recordBtn.y + 30;
             addChild (textInput);
        }

        private function startRecord (e:Event):void
        {
             if (ns)
             {
                   recordBtn.label="Recording";
                   ns.attachAudio (mic);
                   ns.attachCamera (cam);
                   ns.publish (textInput.text,"record");
             }
        }

        private function stopAll (e:Event):void
        {
             playBtn.label="Play";
             recordBtn.label="Record";
             ns.close ();
        }

        private function startPlay (e:Event):void
        {
             if (ns)
             {
                   playBtn.label="Playing";
                   vid2.attachNetStream (ns);
                   ns.play (textInput.text);
             }
        }
  }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Setting Your Camera and Microphone
One of the ongoing challenges for FMS3 developers is optimizing the settings for cameras and microphones. The Camera and Microphone classes provide methods for setting several different parameters. Depending on your media environment— your hardware (Webcams and microphones) and connection bandwidth—the settings will affect your application’s performance.
Every Webcam has a “native” capacity, but whether that capacity can actually be realized is another matter. For example, most USB 2 and IEEE 1394 (FireWire) Webcams list a video capture speed of 30 frames per second (fps) and a video capture resolution of 640 × 480. Chances are that unless you have a pretty hefty bandwidth capability, lots of RAM memory, and a big fat processor, you’re not going to be able to get that type of resolution in even a two-way audio/video chat.
Several Webcams provide the specifications for the “in-between” video capture resolutions.
The following are typical settings built into Webcams and digital video cameras:
  • 160 × 120
  • 176 × 144
  • 320 × 240
  • 360 × 240
  • 352 × 288
  • 640 × 480
The native video capture resolutions are generally set to a 4:3 (width:height) ratio; although it’s not necessary to maintain that ratio, while you’re getting started it’s not a bad idea. FMS3 uses fairly sophisticated algorithms to resolve settings, but by using the 4:3 ratio you’re going to be able to optimize what your camera sees. However, if you’re interested in more details about how the settings work and using different aspect ratios, look at these resources
Unlike many other classes where an object instance is instantiated using a constructor, Camera and Microphone instances use the get( ) method. The parameters for both Camera.getCamera( ) and Microphone.getMicrophone( ) refer to the drivers in one’s local system. Usually, the process is nothing more than using the instantiating process without any parameters, such as,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Camera and Microphone Methods for Setting Parameters
One of the ongoing challenges for FMS3 developers is optimizing the settings for cameras and microphones. The Camera and Microphone classes provide methods for setting several different parameters. Depending on your media environment— your hardware (Webcams and microphones) and connection bandwidth—the settings will affect your application’s performance.
Every Webcam has a “native” capacity, but whether that capacity can actually be realized is another matter. For example, most USB 2 and IEEE 1394 (FireWire) Webcams list a video capture speed of 30 frames per second (fps) and a video capture resolution of 640 × 480. Chances are that unless you have a pretty hefty bandwidth capability, lots of RAM memory, and a big fat processor, you’re not going to be able to get that type of resolution in even a two-way audio/video chat.
Several Webcams provide the specifications for the “in-between” video capture resolutions.
The following are typical settings built into Webcams and digital video cameras:
  • 160 × 120
  • 176 × 144
  • 320 × 240
  • 360 × 240
  • 352 × 288
  • 640 × 480
The native video capture resolutions are generally set to a 4:3 (width:height) ratio; although it’s not necessary to maintain that ratio, while you’re getting started it’s not a bad idea. FMS3 uses fairly sophisticated algorithms to resolve settings, but by using the 4:3 ratio you’re going to be able to optimize what your camera sees. However, if you’re interested in more details about how the settings work and using different aspect ratios, look at these resources
Unlike many other classes where an object instance is instantiated using a constructor, Camera and Microphone instances use the get( ) method. The parameters for both Camera.getCamera( ) and Microphone.getMicrophone( ) refer to the drivers in one’s local system. Usually, the process is nothing more than using the instantiating process without any parameters, such as,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Minimalist Project
Even a minimal project requires sending out an audio/video stream and sending it back in again. The local video doesn’t help at all to see the results of your setting. Thus, you’re going to have to stream in the video you’re sending out to simulate what the person receiving your stream will see. You don’t have many ways to simulate different kinds of connections; if you want to try out different connection speeds, you’ll have to enlist the help of some friends whose connections differ from yours. Still, you can get an idea of what happens with different settings using a LAN or streaming in and out of the same computer. You’ll need the following classes and objects (client-side):
Classes and Methods
NetConnection
NetStream
Camera
setMode( )
setQuality( )
setKeyFrameInterval( )
setMotionLevel( )
Microphone
setMode( )
setQuality( )
setKeyFrameInterval( )
setMotionLevel( )
Video
This first minimalist project lets you hardcode the different parameter values for the camera and microphone and then view the results of your settings. (“Hardcode” refers to directly tying in the parameters using literal values.) Later in this chapter, you’ll be able to experiment with a more robust application.
Before starting, let’s look at the absolute minimum code required to set up your camera and microphone:
  1. Import Camera, Microphone, Video, NetConnection, NetStream, NetStatusEvent and ObjectEncoding packages.
  2. Instantiate Camera and Microphone objects and their key methods for setting their parameters. These are used with your hardware to send out the digital video and sound. A video instance is instantiated by assigning a variable as a Video class instance.
  3. Create a connection to the server (FMS3). This is done with the NetConnection class.
  4. Create a NetStream instance to stream video to the server where it will be streamed back to view the video object.
This code uses two video objects and two net stream objects. One stream captures the audio and video displayed in the local video and sends it out to the server. The other stream object brings the stream in and displays it in the second video. Look at the key camera and microphone settings. You can increase or decrease the values to provide a better picture and motion. A general rule of thumb is that as you increase the quality, you also increase the amount of bandwidth used to stream the audio and video. Likewise, as you decrease some aspect of quality, you decrease the bandwidth.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Dynamically Testing Your Camera and Microphone Settings
To more easily see the effects of different settings, this next application uses minimum code for the actual settings, but it employs several different UI components for user input. The purpose of the application is two-fold. First, it allows you to explore the optimum values for setting your camera and microphone values dynamically. Second, it helps you understand how to use different UI components for making dynamic settings. Before getting started, look at and , an “instance map,” to see what components are used and their instance names. They include two movie clips with embedded video objects and a slider movie clip containing another movie clip used in changing volume.
This application uses the Stage to set up both TextInput and Button components. You need to change some settings to get the component instance names to be recognized by ActionScript 3.0, but you’ll save a lot of time getting the components just where you want them on the Stage and in coding. To get going, follow these steps:
  1. Open a new Flash file and create four layers, naming them from top to bottom, Text, TextInputs, Buttons and Background in the Timeline. Save the file as DyControls.fla..
  2. Drag a Button, TextInput and Slider component from the Components panel to the Library panel.
  3. Select File → Publish Settings → Flash tab → Settings Button and then next to Stage, deselect Automatically Declare Stage Instance. This crucial step enables ActionScript 3.0 to recognize the instance names.
  4. Click the TextInputs layer, and drag ten TextInput components to the Stage, placing them as shown in and . These figures also show the instance names to use for each component’s instance name in the Property inspector.
    Figure : Instance name for Camera input
  5. Click the Buttons layer, and drag five Button components to the Stage, placing them as shown in and . These figures also show the instance names to use for each component’s instance name in the Property inspector.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Key Considerations
This last section briefly considers some elements of the settings you’re making.
fps The number of frames per second acts as a multiplier on your application. A 320 × 240 frame has 320 × 240 pixels to ship across the Internet—about 77 Kbits. A setting of 15 fps = 15 × 77 Kbits —about 1.2 Mbits. With those same conditions, a setting of 30 fps would be about 2.4 Mbits. A smaller window of 160 × 120 requires about 19 Kbitsper frame, so a setting of 15 fps requires 285 Kbits. If the quality of the picture is important but the movement is not, such as in an audio/video chat where only your mouth is moving or you’re sitting quietly listening and looking, you can gear down the fps setting to save bandwidth.
Quality: The quality (amount of compression) affects how good your image is going to look, and how much bandwidth it will consume. In turn, this will affect how much is used in each frame. Higher quality means more bits per frame.
Width and Height: Camera mode settings and video dimensions need not be the same. Your video screen can be set to 160 × 120, but if you set your camera mode to 320 × 240, you’ll get a better picture. Conversely, if you set your mode to 160 × 120 and your video to 320 × 240, you’ll get a bigger video picture but lower quality. However, if you deviate from the 4:3 ratio, you definitely want to match your camera mode settings with the video setting. For example, suppose you want to have a smaller picture with a 2:5 ratio. Your video dimensions should also have a 2:5 ratio. In the application, matching the video to the camera settings is done by the following simple algorithm:
video.width=camera.width;
video.height=camera.height
That makes it easy because the video is simply reflecting the camera’s mode setting.
Silence and Motion Levels: Setting the silence level impacts the amount of bandwidth used. When the sound is below the silence level, no sound is sent. This is a very important setting because it actually affects the amount of bandwidth your application uses. Setting the camera’s activity level works in a similar way, except that it does not affect bandwidth. Rather, when the motion from the camera reaches the level set for detecting motion, the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adjusting Camera and Audio with Flash Media Encoder
Another way to set up and test your adjustments with the camera and microphone is to use the Flash Media Encoder (FME) with a live trial. The importance of testing your streams with a live trial is that when you have a live broadcast, what you see and what the user sees may be very different. Using FME, you can both see the input (local) and the output (streaming). You can use all of the built-in format adjustments in FME. Likewise, you can test your output on another system to be sure everything is the way you want.
In this next example, a digital video camera is connected, and FME provides the native sizes of the camera. A Canon Optura 100 was used in the test with a setting of 360 × 240. This setting is native the camera, and while it does not adhere to the 4:3 ratio but uses a 3:2 ratio instead. To see how the DV camera looks on a remote site, a Macintosh player application displays the output sent by the FME. provides the listing for the remote player:
Example . FMElive.as
package
{
  import flash.display.Sprite;
  import flash.net.NetConnection;
  import flash.net.NetStream;
  import flash.events.NetStatusEvent;
  import flash.media.Video;

  public class FMElive extends Sprite
  {
        private var good:Boolean;
        private var vid:Video;
        private var nc:NetConnection;
        private var ns:NetStream;
        private var rtmpNow:String;
        private var metaSniffer:Object;

        public function FMElive()
        {
             setVid();
             rtmpNow="rtmp://192.168.0.11/fme/viewer";
             nc=new NetConnection();
             nc.addEventListener(NetStatusEvent.NET_STATUS, checkConnect);
             nc.connect(rtmpNow);
        }

        private function getMeta (mdata:Object):void
        {
             //Live
        }

        private function checkConnect(e:NetStatusEvent):void
        {
             good=(e.info.code=="NetConnection.Connect.Success");
             if(good)
             {

                   ns=new NetStream(nc);
                   vid.attachNetStream(ns);
                   ns.play("liveFME");
                   metaCheck();
             }
        }

        private function setVid():void
        {
             vid=new Video();
             vid.x=95;vid.y=80;
             vid.width=360,vid.height=240;
             addChild(vid);
        }

        private function metaCheck():void
        {
             metaSniffer=new Object();
             ns.client=metaSniffer;
             metaSniffer.onMetaData=getMeta;
        }

  }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Nonpersistent Client-Side Remote Shared Objects
The first time I encountered the remote shared object I thought it had to be the most important contribution to the Internet since the invention of the browser. That opinion has changed little over the years, especially in the case of any application that needs to send data and interact with others in a “live” situation.
So what are shared objects and what are they used for? Shared objects are objects that can be displayed and controlled on one browser and seen on another. So if you have an application that displays text using a text input field, you can display that text in both your own browser as well as in all others that are looking at the same application. Besides text, you can move movie clips on one screen, and they move on other screens. You can click a button on one browser to launch an event on all browsers using shared objects.
When a shared object is set up in a Flash Media Server 3 application, it sets up a “subscription” that others who have launched the same application automatically subscribe to. Think of shared objects as magazines and everyone who logs on gets a subscription to the magazine. The “magazines” are delivered in the form of real-time data. So, if you’re sending (sharing) the text in a text field, as soon as you enter the data, it’s seen on the remote computer.
Nonpersistent shared objects are something like variables. When you quit an application, all of the values in the variables disappear. They do not persist. In the same way, the data in a nonpersistent shared object is lost as soon as users leave the application.
Persistent shared objects are more like data in a database. The data from persistent shared objects is stored on the server’s hard drive, and hence, persist. When you have data that you need to access from different sites, persistent shared objects are very handy. However, this chapter deals only with nonpersistent shared objects. In , where more advanced shared objects concepts are discussed, both server-side and persistent shared objects will be examined.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Sharing Data on Multiple Connections
The first time I encountered the remote shared object I thought it had to be the most important contribution to the Internet since the invention of the browser. That opinion has changed little over the years, especially in the case of any application that needs to send data and interact with others in a “live” situation.
So what are shared objects and what are they used for? Shared objects are objects that can be displayed and controlled on one browser and seen on another. So if you have an application that displays text using a text input field, you can display that text in both your own browser as well as in all others that are looking at the same application. Besides text, you can move movie clips on one screen, and they move on other screens. You can click a button on one browser to launch an event on all browsers using shared objects.
When a shared object is set up in a Flash Media Server 3 application, it sets up a “subscription” that others who have launched the same application automatically subscribe to. Think of shared objects as magazines and everyone who logs on gets a subscription to the magazine. The “magazines” are delivered in the form of real-time data. So, if you’re sending (sharing) the text in a text field, as soon as you enter the data, it’s seen on the remote computer.
Nonpersistent shared objects are something like variables. When you quit an application, all of the values in the variables disappear. They do not persist. In the same way, the data in a nonpersistent shared object is lost as soon as users leave the application.
Persistent shared objects are more like data in a database. The data from persistent shared objects is stored on the server’s hard drive, and hence, persist. When you have data that you need to access from different sites, persistent shared objects are very handy. However, this chapter deals only with nonpersistent shared objects. In , where more advanced shared objects concepts are discussed, both server-side and persistent shared objects will be examined.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Instantiating Remote Shared Objects
This chapter will demonstrate three different remote shared objects with minimal code. The first is a pointer that lets you point to any location on another person’s page. This kind of pointer can come in handy if you’re making a presentation to a remote location and you have to point out different things to the audience. Second, you will see how to make a minimal text chat where the text entered into an input text box shows up on all users’ screens. And third, using a shared movie clip, you will see how to open Web pages on remote viewers’ screens. These are all minimal examples, but they show how you can do different things with remote shared objects. The rest is up to your imagination.
When using a class, you can scope the shared object outside the constructor, just as you would any other variable.
private var so:SharedObject;
Instantiating a remote shared object, though, is a little different than most class instances. shows the general format for instantiating a shared object.
Figure : Instantiating SharedObject class
Instead of using the new statement, the getRemote() method creates the remote shared object. Using the same data type (SharedObject), you can also create a local shared object with the method, getLocal(). Given the focus on FMS3, you will not find any examples using local shared objects in this book.
When you set up a shared object instance, you need to set up a storage system based on the shared object’s properties. Unlike earlier versions of Flash Communication Server and Flash Media Server, Flash Media Server 3 uses the SharedObject.setProperty() method to assign values to a shared object property. By assigning different shared object properties you can create slots using most kinds of data types. The following shows a simple property slot:
var memberName:String= name_txt.text;
so.setProperty("cliName", memberName);
The shared object has a data property, cliName. So it now has a storage slot for a string name that can be shared with others connected to the same application. In the same way, you can set up as many slots as your application needs, using the appropriate data type for the data to be stored. Whenever the shared object property changes, it fires a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Minimalist Project for Shared Movie Clip
To see how shared objects work with a remote page, this first minimalist project uses a movie clip as a shared object. This example shows how to set up and move a movie clip around the Stage—your Stage and the Stage of anyone connected to the same shared object. In creating applications that have online slide shows that work something like a PowerPoint presentation, you need all viewers to see the pointer move to the location onscreen where you want them to focus. Using an island movie clip as a pointer, this application has island names in each of the Stage’s four corners. The four names are simply positions on the Stage that let you see that when you move the pointer onscreen, it will go to the same positions on all screens connected to the application. You’ll use these classes and objects for the application:
Classes
NetConnection
SharedObject
NetStatusEvent
SyncEvent
MouseEvent
Objects
Movie Clip (1)
Follow these steps to walk through the project:
  1. Open a new Flash document and save it as MinSOmc.fla.
  2. In the four corners of the Stage, use the Text tool to type the name of four different islands, as shown in .
  3. Draw the image of an island as shown in with the drawing tools. (Alternatively, draw an arrow pointer or anything else.)
  4. Select the shape and press F8 to open the Convert To Symbol dialog box. Type Island in the Name text box and select Movie Clip as the Type. Turn on the Export for ActionScript checkbox. You should now see the class name Island in the Class window with the Base class, flash.display.MovieClip. Click OK and save the file.
  5. Delete the movie clip from the Stage. It will still be in the Library panel as a class, and you can reference it just as any other class.
  6. Open a new ActionScript file and save it as MinSOmc.as.
  7. Add the code in , and save the file again.
Example . MinSOmc.as
package
{
  import flash.display.Sprite;
  import flash.net.SharedObject;
  import flash.events.NetStatusEvent;
  import flash.events.SyncEvent;
  import flash.net.NetConnection;
  import flash.events.MouseEvent;
  //import flash.net.ObjectEncoding;

  public class MinSOmc extends Sprite
  {
        private var pointer_so:SharedObject;
        private var nc:NetConnection;
        private var good:Boolean;
        private var island:Island;

        public function MinSOmc()
        {
             //NetConnection.defaultObjectEncoding=flash.net.ObjectEncoding.AMF0;
             //Connect
             var rtmpNow:String="rtmp://192.168.0.11/basicSO";
             nc=new NetConnection  ;
             nc.connect (rtmpNow);
             nc.addEventListener (NetStatusEvent.NET_STATUS,doSO);
             island=new Island  ;
             addChild (island);
             island.x=200;
             island.y=200;
             island.addEventListener (MouseEvent.MOUSE_DOWN,beginDrag);
             island.addEventListener (MouseEvent.MOUSE_UP,endDrag);
        }

        private function doSO (e:NetStatusEvent):void
        {
             good=e.info.code == "NetConnection.Connect.Success";
             if (good)
             {
                   //Shared object
                   pointer_so=SharedObject.getRemote("point",nc.uri,false);
                   pointer_so.connect (nc);
                   pointer_so.addEventListener (SyncEvent.SYNC,doUpdate);
             }
        }

        private function doUpdate (se:SyncEvent):void
        {
             for (var cl:uint; cl < se.changeList.length; cl++)
             {
                   trace(se.changeList[cl].code);
                   if (se.changeList[cl].code == "change")
                   {
                        switch (se.changeList[cl].name)
                        {
                             case "xpos" :
                                   island.x=pointer_so.data.xpos;
                                   break;
                             case "ypos" :
                                   island.y=pointer_so.data.ypos;
                                   break;
                        }
                   }
             }
        }

        private function beginDrag (e:MouseEvent)
        {
             island.addEventListener (MouseEvent.MOUSE_MOVE,moveMc);
             island.startDrag ();
        }

        private function endDrag (e:MouseEvent)
        {
             island.stopDrag ();
        }

        private function moveMc (e:MouseEvent)
        {
             e.updateAfterEvent ();
             pointer_so.setProperty ("xpos",island.x);
             pointer_so.setProperty ("ypos",island.y);
        }
  }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Minimalist Project for Shared Text
Having seen a minimalist project for a movie clip, you’ll now look at one for sharing text. The concepts are essentially the same, but instead of basing the changes in the shared object slots on the movement of the mouse position on the Stage, the changes are based on typed input by the user.
In this application, the user changes the value of the shared object property attribute (text content) by typing the value and pressing a button to fire a function. The function enters t