Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 20

constant with the capabilities of your target systems and bandwidth. With Flash Communication Server you can throttle the data rate to automatically adjust for high traffic and slow connections. Without Flash Communication Server you are limited to HTTP, and the users will receive the video as they would any other file over HTTP and must wait during slow connections.

Progressive — HTTP

When you use regular HTTP servers to deploy video content, the file is downloaded to the user’s cache. It begins playing as soon as video content is available, which means you can generally begin showing the video almost immediately on your target bandwidth. However, random access of the video is allowed only within the frames that have downloaded already, which means you can’t fast-forward the index of the video to a spot that hasn’t been loaded yet and expect it to automatically rebuffer and start at that new index.

With HTTP you have the option of wrapping your video in an SWF file, making control of the video within a movie clip typical of any movie clip. HTTP is often selected when quality of the final downloaded file is a concern, such as on movie trailer sites. This is considered lossless in that the content is preserved regardless of pauses in download. HTTP-deployed video files will pause rather than drop frames, leaving you with a pristine final file localized to the user’s machine. By using a null netStream object, you can serve an FLV as an HTTP file. You see this in action in a Try It Out section later in this chapter.

HTTP deployment is ideal for known prerecorded content, with known length and file size.

Streaming — Flash Communication Server

When you use Flash Communication Server to deploy video, you are using Real-time Messaging Protocol. This protocol can be compared to a socket server, but with many more features. Flash Communication Server requires the use of the netConnection and netStream object. Random Access is allowed, because a new index request stops the video stream and rebuffers from the requested index point. The file is not downloaded to the user’s cache, and so disk space is not an issue. When data is lost during transmission over RTMP, the client will not ping the server for correction. The lost data is simply ignored, and the video plays on. Because the video is not localized, moving through the track can have noticeable delays and buffering alerts.

This format is ideal for broadcasts of unknown length and high server traffic.

Video Keyframes

To understand keyframes, you must understand a little about how video works on a computer. Video is a very expensive media type. There are trillions of pixels to track in a full-length movie. If you were to record video without any compression, you’d fill your disk space quickly. Some smart folks came up temporal compression, video compression based on keyframing. The term keyframe, when applied to video, is very different than a Flash keyframe. A keyframe in video is a single frame that is used as an index frame to which other frames refer to for pixel information.

Depending on how many keyframes you define, there are perhaps 10, 20, or 40 frames that come after a keyframe, which are not nearly as defined as the keyframe. These frames are called interframes. When a keyframe is reached, the following interframe is compared to the keyframe. A complete image of the

498

Managing Video

fragment interframe and the keyframe is blended to make one consistent image. Each following interframe compares itself to the frame before it. In this way, a small percentage of frames can be defined as whole, and then you can compress your movie with far less data in each frame. This leads to a much smaller file size.

When considering file size, people often overlook keyframes, but they can make a huge difference in file size and performance. The more keyframes you have, the more accurate your video will be to the larger, uncompressed version. However, keyframes are expensive in file size, because they contain 100 percent of the data needed to display the frame. Many keyframes can be expensive to redraw as well, because the video player must redraw the entire frame, rather than regions. Too many keyframes can sometimes be the culprit in choppy video, but too few can be the reason for blocky video, where there aren’t enough keyframes to build accurate frames.

A video with a high amount of motion content requires more keyframes and a higher data rate. Significant degradation of quality may be perceived between two equal-length movies compressed at the same data rate and keyframe frequency. It is important to consider the motion content of the source video. Both the On2 and Spark codecs can insert keyframes when large pixel differences are detected from frame to frame but are bound by the keyframe frequency specified.

Keyframes are also the indexes by which FLV files incrementally rewind and fast-forward. Scrubbing the timeline of an FLV file will reveal only the keyframes. So the more keyframes you have, the smoother the scrubbing appears.

Variable Bit Rate

When you use variable bit rate compression, you are allowing frames that deviate more from the keyframes than others to maintain data, and thus quality. You can discard image data and maintain quality. Variable bit rate is the ideal method and often surprises people when they see the quality difference. Variable bit rate is often called 2 Pass. This is because the encoder is required to analyze the entire file first, deciding where to discard data and where to maintain data. The encoder then compresses the file per frame. This is not ideal when the video must be encoded quickly, but it is perfect for those times you need to deliver high-quality video.

Interlacing

Interlacing is a video method designed for television. All video captured in NTSC or PAL contains interlaced frames. An interlaced frame contains two frames in a single field. They are separated vertically, like blinds, with each image taking up every other horizontal line. You might sometimes view a QuickTime video that seems to have some horizontal artifacts or distortion, and that’s often because the file was not deinterlaced before being compressed. Many capture cards and DV cameras now have halfscreen options, for when you know you will be targeting compressed video formats.

Most video compression tools have deinterlacing methods built in. To display your source video with the best quality possible in Flash, you must understand the condition of your source video and treat it correctly.

Frame Rate

Frame rate is the number of frames to display per second. With Flash, you have the freedom of specifying any frame rate you want, within reason. However, video always will compress better and look better if

499

Chapter 20

the frame rate is maintained. This is especially true for FLV video wrapped in an SWF file. Small incremental changes in frame rate, different from the original uncompressed frame rate, can lead to out-of- synch sound.

Generally you want to choose lower frame rates when all other compression setting options have been exhausted. Choosing a lower frame rate drastically affects the perceived quality of the file but can solve bandwidth issues.

Creating Flash Video

Many products can compress directly to the FLV format. Among them are products from Sorenson and screen capture tools such as Camtasia.

With Flash 8, you have the Flash 8 Video Encoder. Unlike Sorenson, and other solutions, this encoder can produce only FLV files and will not automatically wrap the FLV into an SWF file. This encoder is limited in defining keyframes and variable bit rates. An alternative product is Flix 8 Pro. Flix 8 Pro is similar to Sorenson Squeeze but designed specifically for the On2 codec. Flix 8 Pro allows you to encode to 2 Pass VBR, as well as maintain complete control over keyframes, data rate, and deinterlacing. Flix also allows you to emulate video by converting the video to a series of images while synchronizing the frame rate with sound. You can deploy these emulated videos on any Flash player, including Flash 3! Obviously this is less than ideal because of size concerns and performance, but might be a solution for a specific technology-challenged user base in which Flash 6, 7, or 8 are not available, but 3 and 4 are.

The Flash 8 Video Encoder, which comes with Flash to create FLV video, is used in the examples given here. Look at third-party products and tools if you plan on deploying large amounts of video or when quality control must be granular, such as for Flash 6 on PocketPC.

The Flash Video Encoder also comes with something called CuePoints. CuePoints are inserted into an FLV file with a time index. ActionScript methods are assigned to these CuePoints and are triggered automatically as the video plays. An FLV file can contain 16 CuePoints. If you need more than 16 CuePoints, you’ll want to use an interval method to watch the index of the video to trigger activity at specific times.

For the Flash 8 Video Encoder to function properly, you must have QuickTime installed on your development machine.

Conver ting a Video

Converting video to SWF is exceptionally easy. Some may find the process unwieldy and difficult to control, but Macromedia has gone to great lengths to ensure that the encoder is easy to use and the video it produces is of a good quality.

The first step to using video in Flash is to test it out. Before inserting your favorite video, try a few test videos to help you understand what to expect from Flash video and the quality that can be achieved.

500

Managing Video

Try It Out

Use Flash 8 Video Encoder to Convert a Video to FLV

In this example you create some FLV video for the following sections on how to use Flash Video with ActionScript. If you do not have a movie file in .mov, .mpg, .avi, or other acceptable format, you can use the example on the WROX Beginning ActionScript 2 web site. The movie you choose should be short. Because you’re testing ActionScript here, you don’t want to spend much time perfecting the video.

1.Open the Flash 8 Video Encoder standalone application.

2.If you have never opened this application before, click around the interface and see what you can see. If you know Flix or Sorenson products, you should feel somewhat comfortable with the interface.

3.Click the Add button in the right column. A system browse window opens. Find a video on your system to encode. It is preferable that the source video be fairly uncompressed, so that you are not recompressing an already lossy file.

4.After you select a video, you will see that the status is waiting. Highlight the file by clicking its name in the list.

5.Click the Settings button in the right column to open a preview window and access some options. If the source file is a codec that Flash understands, you see the video in the preview window. Give your video a name in the input text field.

6.Click the Show Advanced Settings button. The window expands to include more options to change the output file.

7.Make sure the On2 codec is selected. Leave the frame rate set to Same As Source.

Keyframe placement is best left to automatic, unless you see problems later.

Choose a Quality setting. The quality setting refers to preset bit rate values. If you do not like the preset values, select Custom and insert a different value. If you plan on playing the file only locally, you can select a high bit rate. If you plan on viewers using modems, it’s best to select a very low rate. You can also resize the video if you want.

8.If you have sound in your file, select the settings you want to use. Keep in mind that sound, like video, can increase size quickly with minor changes to bit rate.

9.After you have the settings the way you want them, close the Settings window by clicking OK. Define where you would like your file to be saved by selecting Edit Preferences and check the Place Output Files In option. A folder browsing window opens; select a folder and click OK.

10.Click the Start Queue button. You are shown a progress bar.

How It Works

How the actual conversion works is a graduate course in codecs. Know that Flash is using QuickTime to read in the source file. What your QuickTime can view, Flash can likely convert. Using your selected settings, it has now created an On2 FLV file to your specifications. Had you been targeting Flash 7 player, you would have wanted to select the Spark codec instead.

501

Chapter 20

Compressing video well is a skill best learned by doing. Try different output settings and save each .flv file with different names indicating the settings you chose. You can use these files later in the following examples to see the differences your changes made to the quality of the video.

Next you see how to prepare your movie for export.

Try It Out

Create an SWF Video for Export

If you have not completed the previous Try It Out, do it now because you’ll be using the FLV file it produces. Otherwise, you can substitute any .flv file.

1.Open a new FLA and save it as myVideo.fla in your work folder.

2.Select File Import Import to Stage.

3.A file browse window opens. Navigate to the FLV file you created in the preceding Try It Out section, select it, and click Open.

4.The Select Video Settings dialog opens. The file path shown should point to the file you selected in step 3. Click Next.

5.The Deployment Settings dialog opens. For this example, select the Embed Video in SWF and Play in Timeline. Click Next.

6.The Embedding Settings dialog opens. For this example, select Symbol Type: Embedded Video. Be sure that Place Instance On Stage and Extend Timeline, If Needed, are both selected, as well as the Embed the Entire Video option. Click Next.

7.Confirm your action. Clicking Next embeds the video in your project. This can be an intensive operation depending on the size and length of your .FLV file. Make sure that you have nothing else running on your computer and save any other work you are doing. Click Finish to confirm that you want to import the video.

8.A progress bar appears. If your video is very small, this won’t take very long. If your video is large, this can take awhile. It is recommend that you leave Flash alone and allow the system to give all resources to Flash during this process by not running any other programs or intensive processes while you wait.

9.When the video is embedded, you see it on the timeline in the center of the stage. Select the video, and you see in the Properties panel that the object type is Embedded Video. You cannot edit this object, but you can move it. You can also see that the timeline that holds the video object is the same length in frames as the video itself. If you change the FPS of your FLA, you will need to adjust the duration of the video object on the timeline.

10.Move the video object to the top-left corner of the stage. Be sure the x,y position of the video is 0,0. You can set this in the Properties panel of the video object.

11.The frame rate of the FLA must match the original frame rate of the FLV file. Select Modify Document and adjust the frame rate as needed. Adjust the duration of the video object on the timeline to match the duration in seconds of the original FLV file.

12.Select Modify Document. Change the height and width dimensions to match the video object. Save your FLA.

502

Managing Video

13.Publish the FLA to SWF format.

14.You can now navigate to the SWF file and open it in the standalone Flash Player to view your video. You’ll notice there are no controls. Don’t worry; you add those in the following sections.

How It Works

In this example you created a simple SWF file that contains video. Using this method you can now import the SWF using loadMovie into any other SWF. You can use standard movie clip controls to play and stop your SWF. However, this wrapping of the FLV wasn’t completely necessary. It is just an option. Embedding an FLV in an SWF severely limits performance and limits you to 16,000 frames, which can be far too short for longer movies. But this method is great for short video files, in which you would like the video to be treated as any other movie clip on the timeline, such as a video augmented navigation or help section.

Also, Sorenson Squeeze and Flix 8 can both automatically wrap an FLV object in an SWF and output only an SWF file. This can be especially helpful because it saves the time it takes to do by hand.

Another task you accomplished is that you saw how you can place video objects directly onto the timeline using the Import option. Instead of resizing the stage, you could have kept the stage as is and placed the video among existing stage elements. This is handy if your short videos will be synchronized with animation, have a more ambient background motion in a larger FLA.

Loading an External Video

You can also load other videos directly into the library using File Import. You can load .mov .avi,

.mpeg, and more. Follow the “Create an SWF Video for Export” Try It Out example, but change the target movie to any video you want. You will be presented with the same options and dialog boxes. However, you will be presented with an extra dialog screen to select the codec and compression settings for your movie. These settings are identical to the settings in the standalone Flash 8 Video Encoder. Using this method of importing your video, you can save time by not creating a separate FLV file. You should only do this if your video clips are very short, and understand that you are increasing your FLA and SWF size greatly.

Expor ting to Video

With Flash you can also create .avi and .mov videos of timeline animations. With Flash 8, you can export timeline animation with an alpha channel. Try creating a simple root timeline animation. Select File Export Export Movie. In the Save dialog, select .avi or .mov as the Save as Type. Name your file and follow the prompts to export the SWF as video.

Try It Out

Playing an SWF Video in a Movie Clip

If you haven’t done the previous Try It Out, in which you were to create an FLV file and then create the myVideo.swf file, you should do so now. You’ll be using that file in this exercise. Move the myVideo

.swf you created to your work folder or to a place from which this example can target it.

503

Chapter 20

1.Open a new FLA and save it as loadSWFvideo.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type in the following ActionScript code:

myMovie = this.createEmptyMovieClip(“clip”, 0);

myMovie.loadMovie(“myVideo.swf”);

3.Select Modify Document and change the frame rate of the FLA to match the frame rate of your myVideo.swf file.

4.Test your work. You should now see your video playing in the top-left corner of the stage.

How It Works

In this example you simply used loadMovie to show your SWF video file. You had to be sure your frame rate matched the frame rate of the movie. If the frame rate did not match, the sound would become out of synch with the video. This is a limitation of using a video exported as SWF. If you had exported from Sorenson Squeeze, this problem would have been less of an issue because of the way Sorenson Squeeze adds the sound track to the SWF.

Because your video is on a timeline, you can use classic movie clip controls like stop, play, gotoAndPlay, gotoAndStop, and so on to control the video.

Because of the limitations of SWF wrapped videos, use FLV wherever possible. FLV has no length limit, and is not tied to the frame rate of your SWF file.

Loading an External FLV File

When using the video object to load FLV files, you actually use three objects in conjunction to create a full set of controls. These objects are netStream, netConnection, and video.

Most of the controls you’ll use to manipulate your FLV file are in netStream. The relevant methods for video in this class are covered in this chapter. The netConnection class is the object that makes the actual connection to the server. The netStream class calls specific objects through that connection.

The netStream Class

The following table describes the netStream class methods:

Method

Return

Description

 

 

 

close()

Nothing

Stops the stream completely.

play()

Nothing

Begins playing the specified object.

pause()

Nothing

Sets the rate at which the microphone should capture sound.

504

 

 

 

Managing Video

 

 

 

 

 

 

 

 

 

Method

Return

Description

 

 

 

 

 

seek()

Nothing

Sends the video to the closest keyframe to the specified seconds.

 

setBufferTime()

Nothing

Specifies how long to buffer data before beginning to play

 

 

 

the file.

 

 

 

 

The pause() method has one parameter, a Boolean. This method is actually a toggle. If the video is playing, calling pause will pause the video. If the video is already paused from a previous pause call, the video will begin playing from where it was last paused. The parameter can be passed as true or false to override the existing toggle state. Here’s the syntax:

Video.pause(ok:Boolean);

The setBufferTime() method has a single parameter, a Number. The number sets the seconds of video that should be downloaded before the video is allowed to play. Here’s the syntax:

Sound.setBufferTime(n:Number);

setBufferTime is useful for throttling the buffer when skips and frequent pauses are detected due to buffer time out. This can be done in conjunction with the onStatus event and the bufferTime and bufferLength properties to change the behavior of the video object.

The following table describes the netStream class properties:

Event

Type

Description

 

 

 

bufferLength

Number

Number of playable seconds currently in the buffer.

bufferTime

Number

Maximum number of seconds that may be buffered.

bytesLoaded

Number

Number of bytes loaded.

bytesTotal

Number

Number of total bytes of the entire video.

currentFps

Number

Current frame rate of the video clip, independent of the SWF

 

 

frame rate.

Time

Number

Current play position in seconds of the media file.

The netStream class has two events:

onStatus — A Function that fires whenever a change to the object is encountered or if an error occurs.

onMetaData — A Function that fires when the FLV file initially loads. This event is not documented by Macromedia but is extremely useful. It returns metadata about your FLV file. Here’s its syntax:

myNetStream.onMetaData = function(meta) { trace(“Duration = “+meta.duration); trace(“Video Rate = “+meta.videodatarate);

505

Chapter 20

trace(“Audio Rate = “+meta.audiodatarate);

};

This event is especially helpful because it enables you to create percentage-complete progress bars or indicators that show the user how long the video is and how much time is left.

Metadata returns the following properties: canSeekToEnd, audiocodecid, audiodelay, audiodatarate, videocodecid, videodatarate, height, width, and duration

The Video Class

The Video class is one of the objects you use to create controls when loading your FLV files. It has two methods: clear() and attachVideo().

clear()

The clear() method clears the image currently being displayed in the video object on the stage. It has no parameters, and it returns nothing. Here’s its syntax:

Video.clear(ok:Boolean);

clear() is useful when you are switching to a new object or need to clear the last frame of video image when a video is done playing.

attachVideo()

The attachVideo() method has a single parameter that must be a netStream object reference. The method uses the netStream object to load and control the video. Here’s the syntax:

Video.attachVideo(myNetStream:netStream);

The method can be passed null to stop the current video and clear all information in the properties of the video object. The netStream object might also be a webcam object.

Video Class Properties

The Video class has quite a few properties that you can use. They’re described in the following table:

Property

Type

Description

 

 

 

smoothing

Boolean

Specifies if the video should be interpolated when scaled.

height

Number

Height of the actual video in pixels, regardless of the _height

 

 

of the video object.

width

Number

Width of the actual video in pixels, regardless of the _width of

 

 

the video object.

deblocking

Number

Specifies what type of deblocking method should be performed

 

 

on the video.

_xmouse

Number

X position of the mouse over the video object.

506

 

 

 

 

Managing Video

 

 

 

 

 

 

 

 

 

 

 

Property

Type

Description

 

 

 

 

 

 

_ymouse

Number

Y position of the mouse over the video object.

 

_xscale

Number

Scale percentage of the width of the video object.

 

_yscale

Number

Scale percentage of the height of the video object.

 

_x

Number

X position of the video object on the stage.

 

_y

Number

Y position of the video object on the stage.

 

_rotation

Number

Number of radians by which the video is rotated.

 

_width

Number

Width of the entire video object.

 

_height

Number

Height of the entire video object.

 

_parent

Object

The object that contains the video object.

 

_visible

Number

Specifies whether the video object is visible.

 

_alpha

Number

Specifies the transparency of the video object.

 

_name

String

Name of the video object.

 

 

 

Try It Out

 

Playing an FLV Video in a Movie Clip

This example uses the FLV file you created earlier in this chapter. If you have not created this video, you can use the video supplied on the Beginning ActionScript 2 web site or make your own. You’ll be importing the FLV file via ActionScript.

1.Open a new FLA and save it as loadFLVvideo.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

var myNetConnect:NetConnection = new NetConnection(); myNetConnect.connect(null);

var myNetStream:NetStream = new NetStream(myNetConnect); clip_video.attachVideo(myNetStream); myNetStream.play(“myVideo.flv”);

3.Open the Library panel. Select the menu display icon in the Library panel title bar. Select New Video. A Setup dialog opens. Be sure to select ActionScript-Controlled. A video symbol will appear in the library. Drag an instance of the video symbol from the library to the stage.

4.In the Properties panel for the video symbol, now on the stage, change the name to clip_video. You can change the height and width of the object to match your external FLV file.

5.Test your work. You should now see your video playing in the top-left corner of the stage.

How It Works

In this example you saw how to import your raw FLV file directly onto the stage at runtime. By using netConnection, you tell the Flash player you’ll be making a network request. Because you aren’t connecting to Flash Communication Server, pass the connect method a null parameter, which stops the

507