NetConnection, NetStream, and the Rich Media Classes

     

NetConnection , NetStream , and the Rich Media Classes

Six classes, listed in Table 22.3, fall into the Media category.

Table 22.3. Media Classes

Object

Represents

Singleton

Camera

Video cameras (Webcams)

Y

Microphone

Microphones

Y

NetConnection

Network Connection

N

NetStream

Channel within a Connection

N

Sound

Sound/music

N

Video

Video source

N( [*] )


[*] not a singleton, but can't create new instances with new keyword

In Flash MX, these classes, with the exception of Sound , were used almost exclusively with the Flash Communication Server (FCS). This is still true for Microphone and Camera.

For a complete list of attributes, methods , and events associated with the Microphone and Camera objects, see Appendix A, "ActionScript Reference."


The other four Media classes are still used with FCS, too. For instance, the Video class can represent a real-time video/audio stream captured by a Webcam/microphone and broadcast via FCS, and the Sound class can represent just the audio portion of that stream. NetConnection is used to establish a connection to the server, and NetStream is used to manage individual video/audio streams.

For a complete list of attributes, methods, and events associated with the NetConnection and NetStream , see Appendix A.


graphics/new_icon.jpg

In addition to the FCS- related application of these classes, in Flash MX 2004, the Sound , Video , NetConnection and NetStream classes, working together, can be used to manage progressively loaded FLV files.


Using NetConnection and NetStream for Progressive Loading

Progressively loaded .flv files give you some of the advantages of streaming video without the video server required for true streaming video.

For instance, one of the big advantages of streaming video is that the video starts to play before it has completely loaded into the player, reducing the amount of time the user has to wait before the video starts playing. As the video plays, loading continues in parallel. A small amount of video/audio content is stored in a memory buffer, giving the player a "head start," with the goal of ensuring that there is always content to play, even if the download halts momentarily.

Progressively loaded .flv files provide all these same advantages. In fact, the resemblance is so close that the progressively loaded .flv is managed as a stream in Flash, using the same NetStream object used to manage streaming video from the Flash Communication Server (FCS).

For an introduction to the new progressive FLV feature, see "A Tale of Two Versions," page 324 , in Chapter 14.


There are five basic steps required to start playing an .flv file:

  1. Create a NetConnection object. For example, var myNetConnection:NetConnection = new NetConnection();

  2. Tell the Flash Player you're not connecting to any FCS application by executing myNetConnection.connect(null);

  3. Create a network stream over the connection. For example, var myNetStream:NetStream = new NetStream(myNetConnection);

  4. Attach the stream to a Video object on the Stage. For example, myVideo.attachVideo(myNetStream); . Note that before you can do to do this, you have to create the Video object in the Library, and drag and drop it onto the Stage. To create a new Video object, click the top-right menu of the Library panel and choose New Video. Select the Video object on the Stage and give it an instance name , such as myVideo , in the Property inspector.

    For an example of a Video in the Library loaded with attachVideo() , see keepwater_embed.fla on the CD.


  5. Use myNetStream.play( flvFileName ) to tell the stream which .flv file to play. This can be a local file, or a remote file specified using a URL (for example, http://www.myDomain.com/myFile.flv ).

The NetStream object is your main tool for managing a video stream ”one stream per NetStream object. When the stream is coming from Flash Communication Server MX, you have to manage the connection with the server, as well; you use a NetConnection object to do that. One connection can contain any number of streams. When you're just loading an .flv file, there's really no management required for the connection. However, you still have to create a NetConnection object to contain the NetStream object(s). The NetConnection object has only one method, connect() , when used with .flv files. You use connect() with a null parameter to tell the Flash Player that you're not connecting to any server application. Thus, the NetConnection -related code looks like this:

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

You can publish the preceding code, and the rest of the code in this section, for Flash Player 6. If you take out the strong data typing, you could also publish for ActionScript 1. Basically, Macromedia just took the existing streaming media framework and applied it to .flv files. There's nothing new about the ActionScript syntax used for "streaming" .flv files.

The NetStream -related code is equally straightforward. The following code creates a new NetStream object in the connection _ nc NetConnection object, attaches the stream to an existing video object on the Stage, and plays a file, myFile.flv , from a Web site:

 var stream_ns:NetStream = new NetStream(connection_nc); myVideo.attachVideo(stream_ns); stream_ns.play("http://www.someDomain.com/myFile.flv"); 

If you want to control the sound separately from the video, create a Sound object associated with the clip, like this:

 var mySound:Sound = new Sound(this); 

Then you can use that Sound object to control volume or other characteristics of the sound.

For more on the Sound class, see "The Sound Class" later in this chapter, page 651 .


For example, the following line sets the sound volume in the video to zero:

 mySound.setVolume (0); // set volume to zero 

In netstream.fla on the CD accompanying this book, you'll find working sample code incorporating NetConnection and NetStream , as well as code that controls audio, using a Sound object associated with a movie clip.

Working with .flv Files and the NetStream Object

In Flash MX, you had two choices for playing a video file in your movie: you could embed it (store it in the SWF) or you could stream it (get real-time video or video on demand from FCS). Embedding lets you see the individual video frames on the Timeline and work with the video using Flash's visual design tools.

graphics/new_icon.jpg

Flash MX 2004 supports embedding with the new Video Import Wizard, which provides fine control over encoding options, scaling and cropping presets, as well as color and brightness settings.


However, with embedding, the browser has to download the entire SWF before the video starts to play. In addition, after about two minutes of continuous video playback, users may experience audio sync problems.

With FCS, video playback starts after a configurable initial pause to fill the video buffer (5 seconds by default). Audio sync is not a problem. However, you have the added expense and complexity of FCS.

Progressive loading offers a third choice: progressive loading of external .flv files either directly from a Web site using HTTP, or locally ”but in either case, without embedding and without the aid of a special-purpose communication server.

One advantage of .flv files is that you can control them with NetStream objects. NetStream objects have a time property that tells you where the playhead is in the video file. Using this information, you can implement time-based control of the video clip or other elements of your movie. For example, you could pause the video clip at 5.5 seconds and display some text relating to the displayed image. Previously, the time-based kind of control was not easy to achieve without FCS.

Another advantage of .flv files is that they enable you to use the new Media Components (and the accompanying Media Behaviors) that come with Flash Professional. The Media Components implement control via time-based Cue Points, which is possible only with NetStream , and therefore only with the file formats supported by NetStream ( .flv and .mp3 ).

Progressively loaded FLV files have other advantages, as well: For instance, they also require less memory than embedded video files; using less memory improves overall movie performance. In addition, rather than running at the same rate as the container movie, as embedded movies do, external FLVs retain their original frame rates, giving you the flexibility to use different frame rates for different clips within the container movie.

Another very useful feature of the NetStream object is the NetStream.setBufferTime() method. The NetStream buffer is a constantly-refilled "reservoir" that provides video to the Video object at a steady rate, compensating for the variable rates at which files typically load. The buffer should be large enough to continue streaming video even if download stops momentarily. The NetStream.setBufferTime() method enables you to set the size of the buffer in seconds. The longer the buffer time, the longer the initial delay while the buffer fills before the video starts playing. However, this initial delay is usually well worth it if it prevents the NetStream buffer from "running dry." If the buffer runs empty, the video pauses while the buffer refills.

You can create an onStatus event handler for the NetStream object that is playing the FLV. The onStatus event fires when a video/audio clip starts or stops playing, and when the clip automatically restarts (which happens if the NetStream buffer runs dry and a pause is required to refill it). For instance, the onStatus event handler receives the NetStream.Play.Start event when loading a particular video. You could use this opportunity to display some informational text about the video.

Both onStatus and setBufferTime are used in netstream .fla on the CD accompanying this book. They are also discussed later in this chapter under "The Video Class," page 656 .


The Sound Class

The Sound class represents sounds such as music, sound effects, or speech.

graphics/new_icon.jpg

The most notable enhancement to the Sound class in Flash MX 2004 is the ability to retrieve ID3 metadata from MP3 files. ID3 metadata embedded in the .mp3 file provides information such as the artist, the genre , and the name of the song. The onID3 event of the Sound class fires when ID3 information is received within a downloaded MP3 file. You access specific metadata items by using the Sound.ID3 object, which has over 40 attributes, listed in Appendix A, under " Sound.ID3 Attributes."


Sound events are introduced in "Sound Events," page 515 , in Chapter 20. Sample movie sound.fla on the CD shows how the sound events are used.


Sound capabilities can be divided into five major categories: creating the Sound object, loading sounds, getting information about sounds, controlling sounds, and using sound events.

Creating the Sound Object

You can create a new Sound object in two ways. One creates a Sound object that controls all sounds in your movie. The other creates a Sound object that controls sounds in a particular movie clip (or on the root). The following examples illustrate these two methods:

 allSounds = new Sound(); // controls all sounds in your movie mcSounds = new Sound("mc1"); // controls sounds in the "mc1" movie clip 

Loading and Attaching Sounds

ActionScript offers two basic options for accessing sounds: attaching them from the Library or loading them externally. When loading externally, you can either load .mp3 files by using the loadSound() method of the Sound class, or else load .flv files (which may contain only audio) by using NetConnection and NetStream .

Using NetConnection and NetStream to load .flv files is described earlier in this chapter, under "NetConnection, NetStream, and the Rich Media Classes , " page 647 , and "Working with .flv Files and the NetStream Object," page 649 .


There is also a non-ActionScript approach to implementing audio in your movie, which involves importing sounds into the Library manually, and dragging and dropping them onto the Stage. See "Importing Sounds," page 412 , in Chapter 18.


You can also load an SWF that contains manually imported audio, loads external audio, or attaches audio from the Library. That approach enables you, for example, to use the MovieClipLoader class to load sound.

You load an external MP3 using the loadSound() method, as follows :

 mySound.loadSound("myTune.mp3", false); 

The first parameter, which is the name of the sound file to load, is in URL format. Here's an example of a full path to a local file, D:\sound\myTune.mp3 :

 mySound.loadSound("file:///D/sound/myTune.mp3", 1); 

Using a domain name:

 mySound.loadSound("http://www.somedomain.com/somesound.mp3", 1); 

And an IP address and port number:

 mySound.loadSound("http://205.188.234.33:8006", 1); 

The second parameter passed to the loadSound() method determines whether the sound loads as a streaming sound ( true or 1 in the second parameter) or an event sound ( false or in the second parameter).

A streaming sound starts playing as soon as the Flash Player has buffered enough of the sound file to play the number of seconds specified in the _soundbuftime global property ”5 seconds, by default. You can change this time as follows:

 _soundbuftime = 15; // buffer enough for 15 seconds of audio 

An event sound doesn't start playing until it is completely loaded.

With a streaming sound, you don't have to tell it to start to play. It does so automatically. Thus, these two lines on a timeline start a sound playing:

 mySound = new Sound(); mySound.loadSound ( "cantata.mp3", true ); // streaming 

Event sounds, on the other hand, need an explicit call to the start() method to start playing. Because an event sound cannot start playing until it is fully loaded, the usual strategy is to put the start method inside an onLoad event handler. The event handler fires when the sound is fully loaded, triggering the start() method, as in this example:

 mySound = new Sound(this); mySound.onLoad = function () {      this.start(); }; mySound.loadSound ( "cantata.mp3", 0 ); // event sound 

You should define the onLoad handler before you load the sound.

The onLoad event also fires if the sound fails to load. To check for failure, use the parameter that is passed to the onLoad callback function. The parameter is a Boolean: true for success and false for failure. For example:

 mySound.onLoad = function (success) {      if (success) {           this.start();      }      else {           // handle the error here      } }; 

You use the attachSound() method to attach sounds from the Library, as follows:

 mySound.attachSound("ByeBye.wav"); 

The single parameter for attachSound() is the linkage ID of the sound file in the Library. You must execute the start() method to start playing an attached sound.

There is another potential source for audio material that can be associated with a Sound object: a real-time audio stream originating either from a local audio source such as a microphone or from the Flash Communication Server.

Here is a complete, working program that creates a movie clip (line 1), assigns the audio stream from the default local microphone to a variable (line 2), attaches the audio stream to the movie clip (line 3), creates a Sound object that controls all sounds in the movie clip (line 4), and uses the Sound object to set the volume of the sound to , thereby completely muting the sound (line 5).

 1: createEmptyMovieClip ("aud", 1); 2: inputMic = Microphone.get(); // capture audio stream 3: aud.attachAudio(inputMic); // attach audio stream to movie clip 4: mySound = new Sound("aud"); // controls all sounds in "aud " movie clip 5: mySound.setVolume (0); // set volume to zero 

graphics/troubleshooting_icon.jpg

Having trouble playing a sound in a movie loaded with MovieClip.loadMovie() ? See the "Troubleshooting" section at the end of this chapter, page 657 .


Controlling Sounds

You can start and stop a sound, as well as control volume, speaker balance, and stereo separation.

When you start a sound, you can optionally specify a starting point in the sound file, in seconds. There is a second optional parameter, as well, which specifies the number of times to loop the file. The format for the start() method is as follows:

 mySound.start(  secondOffset, loop  ) 

In the following example, the sound starts one second into the sound file and loops 10 times. The offset parameter does not cause a delay. The Flash Player simply skips over the designated amount of audio.

 mySound.start(1,10); 

The onSoundComplete event does not fire until the sound has looped the specified number of times.

The stop() method has two formats. When executed without a parameter, the stop() method stops all sounds controlled by a particular Sound object. For example:

 mySound.stop(); // stops all sounds controlled by mySound 

Which sounds are controlled by a particular Sound object depends on how the Sound object was created, as in these examples:

 mySound = new Sound(); // controls all sounds in the movie mySound.stop(); // stops all sounds in the movie mySound = new Sound("mc1"); // controls all sounds in "mc1" movie clip mySound.stop(); // stops all sounds in  "mc1" movie clip 

As described earlier in this chapter, in "Creating the Sound Object," page 651 , a Sound object may control either all sounds in your movie, or just sounds in a particular movie clip.


You can also use a stopAllSounds() global function, which stops all sounds in a movie.

The stop() method has an optional parameter, used only with sounds attached using the attachSound() method. The parameter is the same linkage ID used to attach the sound originally:

 mySound.attachSound("ByeBye"); mySound.stop("ByeBye"); 

When you use the stop() method with a linkage ID parameter, the Sound object on which you execute the stop() method does not have to be the same Sound object that the sound was attached to ( mySound in the preceding example). However, it must be a Sound object that controls the same sounds as mySound . For instance, in the following example, both globalSound1 and globalSound2 control all sounds in the movie. In the following example, when globalSound2 ends, it also stops a sound that is attached to globalSound1 .

 globalSound1 = new Sound(); globalSound2 = new Sound(); globalSound1.attachSound("MyTune.mp3"); globalSound2.attachSound("ByeBye"); globalSound1.start(0,2); globalSound2.start(); globalSound2.onSoundComplete = function() {      globalSound2.stop("MyTune.mp3"); } 

The same approach works if both Sound objects control sounds in the same movie clip.

You set the volume using the setVolume() method, which takes as a parameter a number from 0 to 100, inclusive. The default is 100. For instance, the following sets the volume to half of full volume:

 mySound.setVolume(50); 

You control speaker balance, the relative loudness of each speaker, using the setPan() method. The setPan() method takes one argument, a number from -100 to 100 , inclusive. If the parameter is negative, the amount is subtracted from the right speaker, while the left speaker remains at 100% of the maximum volume. Thus, mySound.setPan(-50) results in the left speaker being on at 100% of maximum, while the right speaker is on at 50% of maximum. Similarly, if the parameter is positive, the number is subtracted from the left speaker, and the right speaker remains at 100% of maximum. Thus, mySound.setPan(25) results in the right speaker being on at 100% of maximum, while the left speaker is on at 75% of maximum.

The maximum volume is either the default of 100 or whatever you have set via setVolume() . Thus, if you set the volume to 0 with a statement like mySound.setVolume(0) , it doesn't matter what you do with setPan() or setTransform() : No sound will be heard .

Here's an example:

 mySound.setPan(100); // left speaker off, right speaker at 100% of max 

With the setPan() method, if you are working with stereo sound, all the sound in the left speaker represents the left stereo channel, and all the sound in the right speaker represents the right stereo channel.

You use the setTransform() method to control stereo separation. To use this method, you first create a generic object with four attributes: ll , lr , rl , and rr . Each property contains a number from 0 to 100, inclusive. The first letter in the property name indicates which speaker the property controls. The second letter indicates which stereo channel the property controls. Thus, ll is left speaker/left channel; lr is left speaker/right channel; and so on.

The following example uses an object literal to create a sound transform object. This sound transform object, when applied to a Sound object, completely suppresses the left speaker and puts 100% of both the left and right channels in the right speaker. This is impossible to accomplish with setPan() , which never puts the left channel in the right speaker.

 soundTransform = { ll : 0 , lr : 0 , rl : 100 , rr : 100 }; 

You apply the soundTransform object to a Sound object as follows:

 mySound.setTransform(soundTransform); 

Getting Information About Sounds

You can monitor the progress of loading sounds, determine when a sound has completed playing, and check speaker balance and stereo separation. You can also find out the duration of a sound and how much of the sound has already played .

You monitor the progress of loading sounds by using the getBytesLoaded() method. You can combine it with the getBytesTotal() method to determine what percentage of the total sound has loaded:

 percentLoaded = getBytesLoaded() / getBytesTotal() * 100; 

You could, for instance, use the percentLoaded variable in the preceding example to determine the size of a progress bar in a sound preloader, providing a visual indication of progress in loading the sound.

The read-only duration and position attributes of the Sound object tell you how long the sound is and how long it has been playing, respectively. Both provide a measure in milliseconds . Both are getter/setter properties, so you shouldn't use the Object.watch() method with either of them. In the following example, the percentPlayed variable could be used to provide a progress bar for playing a sound, as opposed to loading one:

 percentPlayed = mySound.position / mySound.duration * 100; 

The Video Class

The Video class has just two methods and four properties. You already saw, earlier in this chapter, how the attachVideo() method is used to associate a NetStream object with a Video object to stream an .flv file.

For an example of using the attachVideo() method, see "NetConnection, NetStream, and the Rich Media Classes," earlier in this chapter, page 647 .


Before using attachVideo() , you have to create a new Video object. In the top-right menu of the Library panel, click on New Video to create a Video object in the Library. Place an instance of the Video object on the Stage, and give the instance an instance name in the Property inspector.

The attachVideo() method can also be used with a Camera object, but that's typically not useful unless you have a way to broadcast the video stream. For instance, if the instance name is myVideo , this code, placed on the Timeline, gets the video stream from the local default camera:

 myVideo.attachVideo(Camera.get()); 

If you have a Webcam but are not connected to a communication server, the preceding line of code enables you to watch yourself on the screen of your own computer. Have fun!

Tables 22.4 and 22.5 list the properties and methods, respectively, of the Video object.

Table 22.4. Video Properties

Property

Description

deblocking

A number that specifies the behavior for the deblocking filter applied by the video compressor when streaming video. (the default) allows the video compressor to apply the deblocking filter as needed. 1 disables the deblocking filter. 2 forces the compressor to use the deblocking filter. Read-write.

smoothing

A Boolean; the default is false . Specifies whether video should be smoothed (interpolated) when it is scaled. The player must be in high-quality mode for smoothing to work. Read-write.

height

Height in pixels. Read-only.

width

Width in pixels. Read-only.


The deblocking and smoothing attributes of the video object configure video filters to mitigate the "blocky" appearance of highly compressed video. The deblocking filter degrades playback performance, especially on slower machines, and is usually not necessary for high-bandwidth video.

Table 22.5. Video Methods

Name

Format

Description

attachVideo()

myVideoObject.attachVideo( source null)

Specifies a video stream to be displayed in a myVideoObject . source is either a NetStream object or a Camera object that is capturing a video stream. The NetStream object could be playing an FLV file or a stream from FCS. If source is null , the connection to the video object is dropped. This method is unnecessary if the stream is audio-only . myNetStream.play() plays the audio portion of the video stream automatically.

clear

myVideoObject.clear()

Clears the image currently displayed in myVideoObject .Useful,for example,when the connection to the communication server breaks and you want to display standby information without having to hide the video object.communication server breaks and object.




Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net