ActionScript 3.0 Language and Components Reference | All Packages | All Classes | Language Elements | Index | Appendixes | Conventions | Frames No Frames |
NetStream

Package | flash.net
Class | public class NetStream
Inheritance | NetStream EventDispatcher Object

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The NetStream class opens a one-way streaming connection between Flash Player and Flash Media Server, or between Flash Player and the local file system. A NetStream object is a channel within a NetConnection object. This channel can either publish a stream, using `NetStream.publish()`, or subscribe to a published stream and receive data, using `NetStream.play()`. You can publish or play live (real-time) data and previously recorded data. You can also use NetStream objects to send text messages to all subscribed clients (see the `NetStream.send()` method).

Playing external video files provides several advantages over embedding video in a Flash document, such as better performance and memory management, and independent video and Flash frame rates.

Flash Player 9.0.115.0 and later versions support files derived from the standard MPEG-4 container format including F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2 if they contain H.264 video and/or HEAAC v2 encoded audio. H.264 delivers higher quality video at lower bitrates when compared to the same encoding profile in Sorenson or On2. HE-AAC v2 is an extension of AAC (a standard audio format defined in the MPEG-4 video standard) that uses Spectral Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at low bitrates. For information about supported codecs and file formats, see http://www.adobe.com/go/hardware_scaling_en and the Flash Media Server documentation.

The NetStream class provides several methods and properties you can use to track the progress of the file as it loads and plays, and to give the user control over playback (stopping, pausing, and so on).

General workflow for streaming audio or video. The following steps summarize the workflow for publishing real-time audio and video:

1. Create a NetConnection object.
2. Use the `NetConnection.connect()` method to connect to the application instance on the server.
3. Create a NetStream object to create a data stream within the connection.
4. Use the `NetStream.attachAudio()`method to capture and send audio over the stream and the `NetStream.attachCamera()` method to capture and send video.
5. Use the `NetStream.publish()` method to give the stream a unique name and send data over the stream to the server so that others can receive it. You can also record the data as you publish it, so that users can play it back later.

SWF files that subscribe to the stream will use the name passed to `publish()` in their call to `play()` and will call the same `NetConnection.connect()` method as the publisher. They will have to call the `Video.attachNetStream()` method to stream the video and the `NetStream.play()` method to play it.

Using data keyframes with Flash Media Server: After creating the NetConnection and NetStream objects, you can use `NetStream.send()` to add metadata to live audio or video as you stream it to the server. Metadata can be information such as the height or width of a video, its duration, the name of its creator, and so on. To define the metadata, use the special handler name `@setDataFrame` as the first argument to `NetStream.send()`.

Receiving data from a Flash Media Server stream or progressive FLV file: Flash Media Server and FLV files can send event objects containing data for as specific data points during streaming or playback. You can handle data from a stream or FLV file during playback in two ways:

- Associate a client property with an event handler to receive the data object. Use the `NetStream.client` property to assign an object to call specific data handling functions. The object assigned to the `NetStream.client` property can call listen for the following data points: `onCuePoint()`, `onImageData()`, `onMetaData()`, `onPlayStatus()`, and `onTextData()`. Then write procedures within those functions to handle the data object returned from the stream or FLV file during playback. See the `NetStream.client` property for more information.
- Associate a client property with a subclass of the NetStream class, then write an event handler to receive the data object. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

View the examples

See also

flash.media.Video
flash.net.NetConnection
send()
client
onImageData
onMetaData
Basics of video

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | bufferLength : Number [read-only] The number of seconds of data currently in the buffer. | NetStream
|  | bufferTime : Number Specifies how long to buffer messages before starting to display the stream. | NetStream
|  | bytesLoaded : uint [read-only] The number of bytes of data that have been loaded into Flash Player. | NetStream
|  | bytesTotal : uint [read-only] The total size in bytes of the file being loaded into Flash Player. | NetStream
|  | checkPolicyFile : Boolean Specifies whether Flash Player should try to download a URL policy file from the loaded video file's server before beginning to load the video file. | NetStream
|  | client : Object Specifies the object on which callback methods are invoked to handle streaming or FLV file data. | NetStream
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | currentFPS : Number [read-only] The number of frames per second being displayed. | NetStream
|  | farID : String [read-only] The identity of the far end connected to this NetStream. | NetStream
|  | farNonce : String [read-only] A value chosen substantially by the other end of this stream, unique to this connection. | NetStream
|  | info : NetStreamInfo [read-only] Returns class filled with various Quality of Service( statistics) information. | NetStream
|  | liveDelay : Number [read-only] The number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode. | NetStream
|  | maxPauseBufferTime : Number Specifies how long to buffer messages during pause mode. | NetStream
|  | nearNonce : String [read-only] A value chosen substantially by this end of the stream, unique to this connection. | NetStream
|  | objectEncoding : uint [read-only] The object encoding (AMF version) for this NetStream object. | NetStream
|  | peerStreams : Array [read-only] Holds all of the subscribing NetStreams that are listening to this publishing NetStream. | NetStream
|  | prototype : Object [static] A reference to the prototype object of a class or function object. | Object
|  | soundTransform : SoundTransform Controls sound in this NetStream object. | NetStream
|  | time : Number [read-only] The position of the playhead, in seconds. | NetStream

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | NetStream(connection:NetConnection, peerID:String = null) Creates a stream that can be used for playing video files through the specified NetConnection object. | NetStream
|  | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. | EventDispatcher
|  | attachAudio(microphone:Microphone):void Specifies an audio stream sent over the NetStream object, from a Microphone object passed as the source. | NetStream
|  | attachCamera(theCamera:Camera, snapshotMilliseconds:int = -1):void Starts capturing video from a camera, or stops capturing if theCamera is set to null. | NetStream
|  | close():void Stops playing all data on the stream, sets the time property to 0, and makes the stream available for another use. | NetStream
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | onPeerConnect(subscriber:NetStream):Boolean Invoked whenever a peer-publishing stream matches a peer-subscribing stream. | NetStream
|  | pause():void Pauses playback of a video stream. | NetStream
|  | play(... arguments):void Begins playback of video files. | NetStream
|  | play2(param:NetStreamPlayOptions):void This is an enhanced version of the play above which could be used to do all the things play did like begin playback of a video file or queue up another video file and create a playlist. | NetStream
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | publish(name:String = null, type:String = null):void Sends streaming audio, video, and text messages from a client to Flash Media Server, optionally recording the stream during transmission. | NetStream
|  | receiveAudio(flag:Boolean):void Specifies whether incoming audio plays on the stream. | NetStream
|  | receiveVideo(flag:Boolean):void Specifies whether incoming video will play on the stream. | NetStream
|  | receiveVideoFPS(FPS:Number):void Specifies the frame rate for incoming video. | NetStream
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | resume():void Resumes playback of a video stream that is paused. | NetStream
|  | seek(offset:Number):void Seeks the keyframe (also called an I-frame in the video industry) closest to the specified location. | NetStream
|  | send(handlerName:String, ... arguments):void Sends a message on a published stream to all subscribing clients. | NetStream
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | togglePause():void Pauses or resumes playback of a stream. | NetStream
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher

Events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | Dispatched when Flash Player gains operating system focus and becomes active. | EventDispatcher
|  | asyncError | Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. | NetStream
|  | deactivate | Dispatched when Flash Player loses operating system focus and is becoming inactive. | EventDispatcher
|  | ioError | Dispatched when an input or output error occurs that causes a network operation to fail. | NetStream
|  | netStatus | Dispatched when a NetStream object is reporting its status or error condition. | NetStream
|  | onCuePoint | Establishes a listener to respond when an embedded cue point is reached while playing a video file. | NetStream
|  | onImageData | Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is playing. | NetStream
|  | onMetaData | Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. | NetStream
|  | onPlayStatus | Establishes a listener to respond when a NetStream object has completely played a stream. | NetStream
|  | onTextData | Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. | NetStream

Public Constants

| Constant | Defined By
--- | --- | ---
|  | DIRECT_CONNECTIONS : String = "directConnections" [static] The DIRECT_CONNECTIONS string is a static object used as a parameter to the constructor for a NetStream. | NetStream

Property Detail

bufferLength | property

`bufferLength:Number` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The number of seconds of data currently in the buffer. You can use this property with the `bufferTime` property to estimate how close the buffer is to being full — for example, to display feedback to a user who is waiting for data to be loaded into the buffer.

Implementation
`public function get bufferLength():Number`

See also

bufferTime
bytesLoaded

bufferTime | property |

`bufferTime:Number` [read-write]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies how long to buffer messages before starting to display the stream. For example, to make sure that the first 15 seconds of the stream play without interruption, set `bufferTime` to 15; Flash Player begins playing the stream only after 15 seconds of data are buffered.

The default value is 0.1 (one-tenth of a second). To determine the number of seconds currently in the buffer, use the `bufferLength` property.

Note: To avoid distortion when streaming pre-recorded (not live) content, do not set the value of `NetStream.bufferTime` to 0. By default, Flash Player uses an input buffer for pre-recorded content that queues the media data and plays the media properly. For pre-recorded content use the default setting or increase the buffer time.

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer when `NetStream.pause()` is called. Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming playback, which often caused a delay.

For a single pause, the `NetStream.bufferLength` property has a limit of either 60 seconds or twice the value of `NetStream.bufferTime`, whichever value is higher. For example, if `bufferTime` is 20 seconds, Flash Player buffers until `NetStream.bufferLength` is the higher value of either 20*2 (40), or 60, so in this case it buffers until `bufferLength` is 60. If `bufferTime` is 40 seconds, Flash Player buffers until `bufferLength` is the higher value of 40*2 (80), or 60, so in this case it buffers until `bufferLength` is 80 seconds.

The `bufferLength` property also has an absolute limit. If any call to `pause()` causes `bufferLength` to increase more than 600 seconds or the value of `bufferTime` * 2, whichever is higher, Flash Player flushes the buffer and resets `bufferLength` to 0. For example, if `bufferTime` is 120 seconds, Flash Player flushes the buffer if `bufferLength` reaches 600 seconds; if `bufferTime` is 360 seconds, Flash Player flushes the buffer if `bufferLength` reaches 720 seconds.

Tip: You can use `NetStream.pause()` in code to buffer data while viewers are watching a commercial, for example, and then unpause when the main video starts.

For more information about the new pause behavior, see http://www.adobe.com/go/learn_fms_smartpause_en.

Flash Media Server. The buffer behavior depends on whether the buffer time is set on a publishing stream or a subscribing stream. For a publishing stream, `bufferTime` specifies how long the outgoing buffer can grow before Flash starts dropping frames. On a high-speed connection, buffer time should not be a concern; data will be sent almost as quickly as Flash can buffer it. On a slow connection, however, there might be a significant difference between how fast Flash buffers the data and how fast it can be sent to the client.

For a subscribing stream, `bufferTime` specifies how long to buffer incoming data before starting to display the stream. For example, if you want to make sure that the first 15 seconds of the stream play without interruption, set `bufferTime` to 15; Flash will begin playing the stream only after 15 seconds of data have been buffered.

When a recorded stream is played, if `bufferTime` is zero, Flash sets it to a small value (approximately 10 milliseconds). If live streams are later played (for example, from a playlist), this buffer time persists. That is, `bufferTime` remains nonzero for the stream.

Implementation
`public function get bufferTime():Number`
`public function set bufferTime(value:Number):void`

See also

bufferLength
time

bytesLoaded | property |

`bytesLoaded:uint` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The number of bytes of data that have been loaded into Flash Player. You can use this property with the `bytesTotal` property to estimate how close the buffer is to being full — for example, to display feedback to a user who is waiting for data to be loaded into the buffer.

Implementation
`public function get bytesLoaded():uint`

See also

bytesTotal
bufferLength

bytesTotal | property |

`bytesTotal:uint` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The total size in bytes of the file being loaded into Flash Player.

Implementation
`public function get bytesTotal():uint`

See also

bytesLoaded
bufferTime

checkPolicyFile | property |

`checkPolicyFile:Boolean` [read-write]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies whether Flash Player should try to download a URL policy file from the loaded video file's server before beginning to load the video file. This property applies when you are using a NetStream object for progressive video download (standalone files), or when you are loading files that are outside the calling SWF file's own domain. This property is ignored when you are using a NetStream object to get an RTMP asset.

Set this property to `true` when you are loading an video file from outside the calling SWF file's domain and you need to use the `BitmapData.draw()` method for pixel-level access to the video. If you call `BitmapData.draw()` without setting the `checkPolicyFile` property to `true` at loading time, you may get a `SecurityError` exception because the required policy file was not downloaded.

If you don't need pixel-level access to the video you are loading, avoid setting `checkPolicyFile` to `true`. Checking for a policy file consumes network bandwidth and may delay the start of your download.

When you call the `NetStream.play()` method with `checkPolicyFile` set to `true`, Flash Player must either successfully download a relevant URL policy file or determine that no such policy file exists before it begins downloading the object specified in your call to `NetStream.play()`. To verify the existence of a policy file, Flash Player performs the following actions, in this order:

1. Flash Player considers policy files that have already been downloaded.
2. Flash Player tries to download any pending policy files specified in calls to the `Security.loadPolicyFile()` method.
3. Flash Player tries to download a policy file from the default location that corresponds to the URL you passed to `NetStream.play()`, which is `/crossdomain.xml` on the same server as that URL.

In all cases, Flash Player requires that an appropriate policy file exist on the video's server, that it provide access to the object at the URL you passed to `play()` based on the policy file's location, and that it allow the domain of the calling SWF to access the video, through one or more `<allow-access-from>` tags.

If you set `checkPolicyFile` to `true`, Flash Player waits until the policy file is verified before downloading the video. Wait to perform any pixel-level operations on the video data, such as calling `BitmapData.draw()`, until you receive `onMetaData` or `NetStatus` events from your NetStream object.

If you set `checkPolicyFile` to `true` but no relevant policy file is found, you won't receive an error until you perform an operation that requires a policy file, and then Flash Player throws a `SecurityError` exception.

Be careful with `checkPolicyFile` if you are downloading a file from a URL that uses server-side HTTP redirects. Flash Player tries to retrieve policy files that correspond to the initial URL that you specify in `NetStream.play()`. If the final file comes from a different URL because of HTTP redirects, the initially downloaded policy files might not be applicable to the file's final URL, which is the URL that matters in security decisions.

For more information on policy files, see the "Flash Player Security" chapter of Programming ActionScript 3.0.

Implementation
`public function get checkPolicyFile():Boolean`
`public function set checkPolicyFile(value:Boolean):void`

See also

flash.display.BitmapData.draw()
flash.system.Security.loadPolicyFile()
netStatus
onMetaData
play()
Specifying loading context

client | property |

`client:Object` [read-write]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies the object on which callback methods are invoked to handle streaming or FLV file data. The default object is `this`, the NetStream object being created. If you set the `client` property to another object, callback methods are invoked on that other object. The `NetStream.client` object can call the following functions and receive an associated data object: `onCuePoint()`, `onImageData()`, `onMetaData()`, `onPlayStatus()`, and `onTextData()`.

To associate the `client` property with an event handler:

1. Create an object and assign it to the `client` property of the NetStream object:

            var customClient:Object = new Object();
            my_netstream.client = customClient;

2. Assign a handler function for the desired data event as a property of the client object:

            customClient.onImageData = onImageDataHandler;

3. Write the handler function to receive the data event object, such as:

             public function onImageDataHandler(imageData:Object):void {
                     trace("imageData length: " + imageData.data.length);
             }

When data is passed through the stream or during playback, the data event object (in this case the `imageData` object) is populated with the data. See the `onImageData` description, which includes a full example of an object assigned to the `client` property.

To associate the `client` property with a subclass:

1. Create a subclass with a handler function to receive the data event object:

            class CustomClient {
               public function onMetaData(info:Object):void {
                   trace("metadata: duration=" + info.duration + " framerate=" + info.framerate);
            }

2. Assign an instance of the subclass to the `client` property of the NetStream object:

            my_netstream.client = new CustomClient();

When data is passed through the stream or during playback, the data event object (in this case the `info` object) is populated with the data. See the class example at the end of the NetStream class, which shows the assignment of a subclass instance to the `client` property.

Implementation
`public function get client():Object`
`public function set client(value:Object):void`
Throws

| `TypeError` — The `client` property must be set to a non-null object.

See also

onCuePoint
onImageData
onMetaData
onPlayStatus
onTextData

currentFPS | property |

`currentFPS:Number` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The number of frames per second being displayed. If you are exporting video files to be played back on a number of systems, you can check this value during testing to help you determine how much compression to apply when exporting the file.

Implementation
`public function get currentFPS():Number`

farID | property |

`farID:String` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

The identity of the far end connected to this `NetStream`. Defined only for RTMFP.

Implementation
`flash10 function get farID():String`

farNonce | property |

`farNonce:String` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

A value chosen substantially by the other end of this stream, unique to this connection. Appears to the other end as its `nearNonce`. Only defined for RTMFP connections.

Implementation
`flash10 function get farNonce():String`

info | property |

`info:NetStreamInfo` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

Returns class filled with various Quality of Service( statistics) information. Whenever this call is made, NetStream takes a snapshot of the current state and provides it through the various properties of the `NetStreamInfo` class.

Implementation
`flash10 function get info():NetStreamInfo`

See also

NetStreamInfo

liveDelay | property |

`liveDelay:Number` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode. This property specifies the current network transmission delay (lag time).

This property is intended primarily for use with a server such as Flash Media Server; for more information, see the class description.

You can get the value of this property to roughly gauge the transmission quality of the stream and communicate it to the user.

Implementation
`public function get liveDelay():Number`

maxPauseBufferTime | property |

`maxPauseBufferTime:Number` [read-write]

Specifies how long to buffer messages during pause mode. This could be used to limit how much buffering is done during pause mode by setting the max value of the buffer that should be buffered. As soon as the `NetStream.bufferLength` value reaches this limit it stops buffering. If this value is not set it defaults the limit to the max of the value of 60 seconds or two times the value of `NetStream.bufferTime` on each pause as mentioned above

Implementation
`flash10 function get maxPauseBufferTime():Number`
`flash10 function set maxPauseBufferTime(value:Number):void`

nearNonce | property |

`nearNonce:String` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

A value chosen substantially by this end of the stream, unique to this connection. Appears to the other end as its `farNonce`. Only defined for RTMFP connections.

Implementation
`flash10 function get nearNonce():String`

objectEncoding | property |

`objectEncoding:uint` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The object encoding (AMF version) for this NetStream object. The NetStream object inherits its `objectEncoding` value from the associated NetConnection object. It's important to understand this property if your ActionScript 3.0 SWF file needs to communicate with servers released prior to Flash Player 9. For more information, see the `objectEncoding` property description in the NetConnection class.

The value of this property depends on whether the stream is local or remote. Local streams, where `null` was passed to the `NetConnection.connect()` method, return the value of `NetConnection.defaultObjectEncoding`. Remote streams, where you are connecting to a server, return the object encoding of the connection to the server.

If you try to read this property when not connected, or if you try to change this property, Flash Player throws an exception.

Implementation
`public function get objectEncoding():uint`

See also

NetConnection.objectEncoding
ObjectEncoding

peerStreams | property |

`peerStreams:Array` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

Holds all of the subscribing NetStreams that are listening to this publishing NetStream.

Implementation
`flash10 function get peerStreams():Array`

soundTransform | property |

`soundTransform:SoundTransform` [read-write]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Controls sound in this NetStream object. For more information, see the SoundTransform class.

Implementation
`public function get soundTransform():SoundTransform`
`public function set soundTransform(value:SoundTransform):void`

See also

flash.media.SoundTransform

time | property |

`time:Number` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The position of the playhead, in seconds.

Flash Media Server For a subscribing stream, the number of seconds the stream has been playing. For a publishing stream, the number of seconds the stream has been publishing. This number is accurate to the thousandths decimal place; multiply by 1000 to get the number of milliseconds the stream has been playing.

For a subscribing stream, if the server stops sending data but the stream remains open, the value of `time` stops incrementing. When the server begins sending data again, the value continues incrementing from where it left off plus the time that elapsed while no data was sent.

The value of `time` continues to increment when the stream switches from one playlist element to another. This property is set to 0 when `NetStream.play()` is called with `reset` set to `1` or `true`, or when `NetStream.close()` is called.

Implementation
`public function get time():Number`

See also

bufferLength
bytesLoaded
Constructor Detail

NetStream | () | Constructor

`public function NetStream(connection:NetConnection, peerID:String = null)`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Creates a stream that can be used for playing video files through the specified NetConnection object.

For information about supported codecs and file formats, see http://www.adobe.com/go/hardware_scaling_en and the Flash Media Server documentation.

Parameters

| `connection:NetConnection` — A NetConnection object.
| `peerID:String` (default = `null`)`` — Set to NULL for a connection to FMS. For publishing directly to peers, specify `NetStream.DIRECT_CONNECTIONS`. To play directly from a specific peer, specify that peer's identity (see `NetConnection.nearID` and `NetConnection.farID`). `NetConnection.protocol` must be "rtmfp" if peerID is not NULL. The `peerID` parameter is ignored for non RTMFP connections.

Throws

| `ArgumentError` — The NetConnection instance is not connected.

See also

flash.net.NetConnection
flash.media.Video.attachCamera()
Method Detail

attachAudio | () | method

`public function attachAudio(microphone:Microphone):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies an audio stream sent over the NetStream object, from a Microphone object passed as the source. This method is available only to the publisher of the specified stream.

The `attachAudio` method is intended for use with Flash Media Server. This method is often called by a user sending live audio (or live video with audio) from a client computer to the server.

You can call this method before or after you call the `publish()` method and actually begin transmitting. Subscribers who want to hear the audio must call the `NetStream.play()` method. You can control the sound properties of this audio stream through the `soundTransform` property of the specified Microphone object.

Parameters

| `microphone:Microphone` — The source of the audio stream to be transmitted.

See also

play()
flash.media.Microphone

attachCamera | () | method |

`public function attachCamera(theCamera:Camera, snapshotMilliseconds:int = -1):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Starts capturing video from a camera, or stops capturing if `theCamera` is set to `null`. This method is available only to the publisher of the specified stream.

This method is intended for use with Flash Media Server; for more information, see the class description.

After attaching the video source, you must call `NetStream.publish()` to begin transmitting. Subscribers who want to display the video must call the `NetStream.play()` and `Video.attachCamera()` methods to display the video on the Stage.

You can use `snapshotMilliseconds` to send a single snapshot (by providing a value of 0) or a series of snapshots — in effect, time-lapse footage — by providing a positive number that adds a trailer of the specified number of milliseconds to the video feed. The trailer extends the display time of time the video message is displayed. By repeatedly calling `attachCamera()` with a positive value for `snapshotMilliseconds`, the sequence of alternating snapshots and trailers create time-lapse footage. For example, you could capture one frame per day and append it to a video file. When a subscriber plays the file, each frame remains onscreen for the specified number of milliseconds and then the next frame is displayed.

The purpose of the `snapshotMilliseconds` parameter is different from the `fps` parameter you can set with `Camera.setMode()`. When you specify `snapshotMilliseconds`, you control how much time elapses between recorded frames. When you specify `fps` using `Camera.setMode()`, you are controlling how much time elapses during recording and playback.

For example, suppose you want to take a snapshot every 5 minutes for a total of 100 snapshots. You can do this in two ways:

- You can issue a `NetStream.attachCamera(myCamera, 500)` command 100 times, once every 5 minutes. This takes 500 minutes to record, but the resulting file will play back in 50 seconds (100 frames with 500 milliseconds between frames).
- You can issue a `Camera.setMode()` command with an `fps` value of 1/300 (one per 300 seconds, or one every 5 minutes), and then issue a `NetStream.attachCamera(source)` command, letting the camera capture continuously for 500 minutes. The resulting file will play back in 500 minutes — the same length of time that it took to record — with each frame being displayed for 5 minutes.

Both techniques capture the same 500 frames, and both approaches are useful; the approach to use depends primarily on your playback requirements. For example, in the second case, you could be recording audio the entire time. Also, both files would be approximately the same size.

Parameters

| `theCamera:Camera` — The source of the video transmission. Valid values are a Camera object (which starts capturing video) and `null`. If you pass `null`, Flash Player stops capturing video, and any additional parameters you send are ignored.
| `snapshotMilliseconds:int` (default = `-1`)`` — Specifies whether the video stream is continuous, a single frame, or a series of single frames used to create time-lapse photography. If you omit this parameter, Flash Player captures all video until you pass a value of `null` to `attachCamera`. If you pass 0, Flash Player captures only a single video frame. Use this value to transmit "snapshots" within a preexisting stream. Flash interprets invalid, negative, or nonnumeric arguments as 0. If you pass a positive number, Flash captures a single video frame and then appends a pause of the specified length as a trailer on the snapshot. Use this value to create time-lapse photography effects.

close | () | method |

`public function close():void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Stops playing all data on the stream, sets the `time` property to 0, and makes the stream available for another use. This method also deletes the local copy of a video file that was downloaded through HTTP. Although Flash Player deletes the local copy of the file that it creates, a copy might persist in the browser's cache directory. If you must completely prevent caching or local storage of the video file, use Flash Media Server.

When using Flash Media Server, this method is invoked implicitly when you call `NetStream.play()` from a publishing stream or `NetStream.publish()` from a subcribing stream. Please note that:

- If `close()` is called from a publishing stream, the stream stops publishing and the publisher can now use the stream for another purpose. Subscribers no longer receive anything that was being published on the stream, because the stream has stopped publishing.
- If `close()` is called from a subscribing stream, the stream stops playing for the subscriber, and the subscriber can use the stream for another purpose. Other subscribers are not affected.
- You can stop a subscribing stream from playing, without closing the stream or changing the stream type by using `flash.net.NetStream.play(false)`.

See also

pause()
play()

onPeerConnect | () | method |

`flash10 function onPeerConnect(subscriber:NetStream):Boolean`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

Invoked whenever a peer-publishing stream matches a peer-subscribing stream. Before the subscriber is hooked up to the publisher, this method is called to allow the ActionScript code fine access control for peer-to-peer publishing. Example code as to how to create such a callback follows: var c:Object = new Object; c.onPeerConnect = function(subscriber:NetStream):Boolean { if (accept) return true; else return false; }; m_netStream.client = c; If a peer-publisher does not implement this method, then all peers are allowed to play any published content.

Parameters

| `subscriber:NetStream`

Returns

| `Boolean`

pause | () | method |

`public function pause():void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Pauses playback of a video stream. Calling this method does nothing if the video is already paused. To resume play after pausing a video, call `resume()`. To toggle between pause and play (first pausing the video, then resuming), call `togglePause()`.

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer when `NetStream.pause()` is called. Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming playback, which often caused a delay.

For a single pause, the `NetStream.bufferLength` property has a limit of either 60 seconds or twice the value of `NetStream.bufferTime`, whichever value is higher. For example, if `bufferTime` is 20 seconds, Flash Player buffers until `NetStream.bufferLength` is the higher value of either 20*2 (40), or 60, so in this case it buffers until `bufferLength` is 60. If `bufferTime` is 40 seconds, Flash Player buffers until `bufferLength` is the higher value of 40*2 (80), or 60, so in this case it buffers until `bufferLength` is 80 seconds.

The `bufferLength` property also has an absolute limit. If any call to `pause()` causes `bufferLength` to increase more than 600 seconds or the value of `bufferTime` * 2, whichever is higher, Flash Player flushes the buffer and resets `bufferLength` to 0. For example, if `bufferTime` is 120 seconds, Flash Player flushes the buffer if `bufferLength` reaches 600 seconds; if `bufferTime` is 360 seconds, Flash Player flushes the buffer if `bufferLength` reaches 720 seconds.

Tip: You can use `NetStream.pause()` in code to buffer data while viewers are watching a commercial, for example, and then unpause when the main video starts.

See also

close()
play()
resume()
togglePause()
bufferLength
bufferTime

play | () | method |

`public function play(... arguments):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Begins playback of video files.

For information about supported codecs and file formats, see http://www.adobe.com/go/hardware_scaling_en and the Flash Media Server documentation.

To view video data, you must create a Video object and call the `Video.attachNetStream()` method; audio being streamed with the video, or a file that contains only audio, is played automatically. To stream audio from a microphone, use the `NetStream.attachAudio()` method and control some aspects of the audio through the Microphone object.

To control the audio associated with a video file, you can use the `DisplayObjectContainer.addChild()` method to route the audio to an object on the display list; you can then create a Sound object to control some aspects of the audio. For more information, see the `DisplayObjectContainer.addChild()` method.

If the video file can't be found, the `netStatus` event is dispatched. To stop a stream that is currently playing, use the `close()` method.

When you use this method without Flash Media Server, consider the Flash Player security model. A SWF file in the local-trusted or local-with-networking sandbox can load and play a video file from the remote sandbox, but cannot access the remote file's data without explicit permission in the form of a URL policy file. Also, you can prevent a SWF file from using this method by setting the `allowNetworking` parameter of the `object` and `embed` tags in the HTML page that contains the SWF content.

For more information related to security, see the following:

- The security chapter in the Programming ActionScript 3.0 book and the latest comments on LiveDocs
- The Flash Player Developer Center Topic: Security
- The `NetStream.checkPolicyFile` property.

Parameters

| `... arguments` — The location of the video file to play as a string or variable. You can play local video files that are stored in the same directory as the SWF file or in a subdirectory; however, you can't navigate to a higher-level directory. Flash Media Server To play video files on Flash Media Server, specify the name of the stream without a file extension (for example, `bolero`). To play MP3 files, use `mp3:` before the stream name. To play the ID3 tags of MP3 files, use `id3:` before the stream name. With Flash Media Server, `play()` takes the following arguments:
Name | Required | Description
--- | --- | ---
`name:Object` | Required | The name of a recorded file without a file extension, an identifier for live data published by `NetStream.publish()`, or `false`. To play MP3 files, use `mp3` before the name. To play the ID3 tag of an MP3 file, use `id3:` before the name. If `false`, the stream stops playing and any additional parameters are ignored.
`start:Number` | Optional | The start time, in seconds. Allowed values are -2, -1, 0, or a positive number. The default value is -2, which looks for a live stream, then a recorded stream, and if it finds neither, opens a live stream. If -1, plays only a live stream. If 0 or a positive number, plays a recorded stream, beginning `start` seconds in.
`len:Number` | Optional if `start` is specified. | The duration of the playback, in seconds. Allowed values are -1, 0, or a positive number. The default value is -1, which plays a live or recorded stream until it ends. If 0, plays a single frame that is `start` seconds from the beginning of a recorded stream. If a positive number, plays a live or recorded stream for `len` seconds.
`reset:Object` | Optional if `len` is specified. | Whether to clear a playlist. The default value is 1 or `true`, which clears any previous `play` calls and plays `name` immediately. If 0 or `false`, adds the stream to a playlist. If 2, maintains the playlist and returns all stream messages at once, rather than at intervals. If 3, clears the playlist and returns all stream messages at once.

Throws

| `SecurityError` — Local untrusted SWF files cannot communicate with the Internet. You can work around this restriction by reclassifying this SWF file as local-with-networking or trusted.
| `ArgumentError` — At least one parameter must be specified.
| `Error` — The NetStream Object is invalid. This may be due to a failed NetConnection.

See also

DisplayObjectContainer.addChild()
checkPolicyFile
Flash Player security
Example
Flash Media Server This example plays a recorded stream, starting at the beginning, for up to 100 seconds:

      ns.play("record1", 0, 100, true);

Flash Media Server This example plays a live stream published by a client, from beginning to end, starting immediately and clearing any previous streams:

      ns.play("stephen");

play2 | () | method |

`flash10 function play2(param:NetStreamPlayOptions):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

This is an enhanced version of the `play` above which could be used to do all the things `play` did like begin playback of a video file or queue up another video file and create a playlist. When used with Flash Media Server it also adds capability to dynamically transition to a new file at the server seamlessly at the player, which could be used to switch streams of the same content encoded at different bit rates to dynamically adapt to the changing network conditions or swap out streams from a playlist. For more description and options available see the documentation for the `NetStreamPlayOptions` and `NetStreamPlayTransitions` see NetStreamPlayOptions see NetStreamPlayTransitions

Parameters

| `param:NetStreamPlayOptions`

publish | () | method |

`public function publish(name:String = null, type:String = null):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Sends streaming audio, video, and text messages from a client to Flash Media Server, optionally recording the stream during transmission. This method is available only to the publisher of the specified stream.

Don't use this method to let a client play a stream that has already been published and recorded. Instead, create a NetStream instance for that client and call the `play()` method:

      var subscribeNS:NetStream = new NetStream(myNetConnection);
      subscribeNS.play("streamToPlay");

When you record a stream using Flash Media Server, the server creates a file and stores it in a subdirectory in the application's directory on the server. Each stream is stored in a directory whose name matches the application instance name passed to `NetConnection.connect()`. The server creates these directories automatically; you don't have to create one for each application instance. For example, the following code shows how you would connect to a specific instance of an application stored in a directory named lectureSeries in your applications directory. A file named lecture.flv is stored in a subdirectory named /yourAppsFolder/lectureSeries/streams/Monday:

      var myNC:NetConnection = new NetConnection();
      myNC.connect("rtmp://server.domain.com/lectureSeries/Monday");
      var myNS:NetStream = new NetStream(myNC);
      myNS.publish("lecture", "record");

The following example shows how to connect to a different instance of the same application but issue an identical publish command. A file named lecture.flv is stored in a subdirectory named /yourAppsFolder/lectureSeries/streams/Tuesday.

      var myNC:NetConnection = new NetConnection();
      myNC.connect("rtmp://server.domain.com/lectureSeries/Tuesday");
      var myNS:NetStream = new NetStream(my_nc);
      myNS.publish("lecture", "record");

If you don't pass a value for the instance name, that matches the value passed to the `name` property is stored in a subdirectory named /yourAppsFolder/appName/streams/_definst_ (for "default instance"). For more information on using instance names, see the `NetConnection.connect()` method. For information on playing back video files, see the `NetStream.play()` method.

When a Flash Media Server application client calls `publish()`, the application receives an `onPublish` event. The application must handle the event in a server-side script. When the client stops publishing, the application receives an `onUnpublish` event. For more information, see the Flash Media Server Server-Side ActionScript Language Reference.

This method can dispatch a `netStatus` event with several different information objects. For example, if someone is already publishing on a stream with the specified name, the `netStatus` event is dispatched with a code property of `NetStream.Publish.BadName`. For more information, see the `netStatus` event.

Parameters

| `name:String` (default = `null`)`` — A string that identifies the stream. Clients that subscribe to this stream must pass this same name when they call `NetStream.play()`. You don't need to include a file extension for the stream name. Don't follow the stream name with a "/". For example, don't use the stream name `"bolero/"`.
| `type:String` (default = `null`)`` — A string that specifies how to publish the stream. Valid values are "`record`", "`append`", and "`live`". The default value is "`live`". If you pass "`record`", Flash Player publishes and records live data, saving the recorded data to a new file with a name matching the value passed to the `name` parameter. The file is stored on the server in a subdirectory within the directory that contains the server application. If the file already exists, it is overwritten. If you pass "`append`", Flash Player publishes and records live data, appending the recorded data to a file with a name that matches the value passed to the `name` parameter, stored on the server in a subdirectory within the directory that contains the server application. If no file with a matching name the `name` parameter is found, it is created. If you omit this parameter or pass "`live`", Flash Player publishes live data without recording it. If a file with a name that matches the value passed to the `name` parameter exists, it is deleted.

See also

NetConnection.connect()
play()
netStatus

receiveAudio | () | method |

`public function receiveAudio(flag:Boolean):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies whether incoming audio plays on the stream. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

This method is intended primarily for use with Flash Media Server; for more information, see the class description.

You can call this method before or after you call the `NetStream.play()` method and actually begin receiving the stream. For example, you can attach these methods to a button the user clicks to mute and unmute the incoming audio stream.

If the specified stream contains only audio data, passing a value of `false` to this method stops `NetStream.time` from further incrementing.

Parameters

| `flag:Boolean` — Specifies whether incoming audio plays on the stream (`true`) or not (`false`). The default value is `true`.

receiveVideo | () | method |

`public function receiveVideo(flag:Boolean):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies whether incoming video will play on the stream. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

This method is intended primarily for use with Flash Media Server; for more information, see the class description.

You can call this method before or after you call the `NetStream.play()` method and actually begin receiving the stream. For example, you can attach these methods to a button the user presses to show or hide the incoming video stream.

If the specified stream contains only video data, passing a value of `false` to this method stops `NetStream.time` from further incrementing.

Parameters

| `flag:Boolean` — Specifies whether incoming video plays on this stream (`true`) or not (`false`). The default value is `true`.

receiveVideoFPS | () | method |

`public function receiveVideoFPS(FPS:Number):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Specifies the frame rate for incoming video. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

This method is intended primarily for use with Flash Media Server; for more information, see the class description.

You can call this method before or after you call the `NetStream.play()` method and actually begin receiving the stream. For example, you can attach these methods to a text field where the user can set the incoming video frame rate.

To stop receiving video, pass 0 for FPS. To determine the current frame rate, use `NetStream.currentFPS`.

If you pass a value to the `FPS` parameter to limit the frame rate of the video, Flash Media Server attempts to reduce the frame rate while preserving the integrity of the video. The server sends the minimum number of frames needed to satisfy the desired rate between every two keyframes. Keep in mind, however, that i-frames (or intermediate frames) must be sent contiguously; otherwise, the video will be corrupted. Therefore, the desired number of frames is sent immediately and contiguously following a keyframe. Since the frames are not evenly distributed, the motion appears smooth in segments punctuated by stalls.

Parameters

| `FPS:Number` — Specifies the frame rate per second at which the incoming video will play.

resume | () | method |

`public function resume():void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Resumes playback of a video stream that is paused. If the video is already playing, calling this method does nothing.

See also

close()
pause()
play()
togglePause()

seek | () | method |

`public function seek(offset:Number):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Seeks the keyframe (also called an I-frame in the video industry) closest to the specified location. The keyframe is placed at an offset, in seconds, from the beginning of the stream.

Video streams are usually encoded with two types of frames, keyframes (or I-frames) and P-frames. A keyframe contains an entire image, while a P-frame is an interim frame that provides additional video information between keyframes. A video stream typically has a keyframe every 10 to 50 frames.

On Flash Media Server, the behavior of `seek()` is controlled by the value of the `EnhancedSeek` element in the `Application.xml` configuration file.

If `EnhancedSeek` is `false`, the server uses normal seek mode. In normal seek mode, the server starts streaming from the nearest keyframe. For example, if a video has keyframes at 0 and 10 seconds, a seek to 4 seconds causes playback to start at 4 seconds using the keyframe at 0 seconds. The video stays frozen until it reaches the next keyframe at 10 seconds. To get a better seeking experience, you need to reduce the keyframe interval. In normal seek mode, you cannot start the video at a point between the keyframes.

If `EnhancedSeek` is `true`, the default value, the server generates a new keyframe at `offset` based on the previous keyframe and any intervening P-frames. However, this creates a high processing load on the server, and distortion might occur in the generated keyframe. If the video codec is On2, the keyframe before the seek point and any P-frames between the keyframe and the seek point are sent to the client.

Parameters

| `offset:Number` — The approximate time value, in seconds, to move to in a video file. With Flash Media Server, if `<EnhancedSeek>` is set to `true` in the Application.xml configuration file (which it is by default), the server generates a keyframe at `offset`. To return to the beginning of the stream, pass 0 for `offset`. To seek forward from the beginning of the stream, pass the number of seconds to advance. For example, to position the playhead at 15 seconds from the beginning (or the keyframe before 15 seconds), use `myStream.seek(15)`. To seek relative to the current position, pass `NetStream.time + n` or `NetStream.time - n` to seek `n` seconds forward or backward, respectively, from the current position. For example, to rewind 20 seconds from the current position, use `NetStream.seek(NetStream.time - 20).`

See also

play()
time

send | () | method |

`public function send(handlerName:String, ... arguments):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Sends a message on a published stream to all subscribing clients. This method is available only to the publisher of the specified stream, and is intended for use with Flash Media Server. To process and respond to this message, create a handler on the `NetStream` object, for example, `ns.HandlerName`.

Flash Player does not serialize methods or their data, object prototype variables, or non-enumerable variables. For display objects, Flash Player serializes the path but none of the data.

You can call the `send()` method to add data keyframes to a live stream sent to Flash Media Server. A data keyframe is a message a publisher adds to a live stream. Data keyframes are typically used to add metadata to a live stream before data is captured for the stream from camera and microphone. A publisher can add a data keyframe at any time while the live stream is being published. The data keyframe is saved in the server's memory as long as the publisher is connected to the server.

Clients who are subscribed to the live stream before a data keyframe is added receive the keyframe as soon as it is added. Clients who subscribe to the live stream after the data keyframe is added receive the keyframe when they subscribe.

To add a keyframe of metadata to a live stream sent to Flash Media Server, use `@setDataFrame` as the handler name, followed by two additional arguments, for example:

      var ns:NetStream = new NetStream(nc);
      ns.send("@setDataFrame", "onMetaData", metaData);

The `@setDataFrame` argument refers to a special handler built in to Flash Media Server. The `onMetaData` argument is the name of a callback function in your client application that listens for the `onMetaData` event and retrieves the metadata. The third item, `metaData`, is an instance of `Object` or `Array` with properties that define the metadata values. Publishers should set property names that subscribers can easily understand; see the Flash Media Server documentation for a list of suggested property names.

Use `@clearDataFrame` to clear a keyframe of metadata that has already been set in the stream:

      ns.send("@clearDataFrame", "onMetaData");

Parameters

| `handlerName:String` — The message to be sent; also the name of the ActionScript handler to receive the message. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the stream object. Do not use a reserved term for a handler name. For example, using "`close`" as a handler name will cause the method to fail. With Flash Media Server, use `@setDataFrame` to add a keyframe of metadata to a live stream or `@clearDataFrame` to remove a keyframe.
| `... arguments` — Optional arguments that can be of any type. They are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly. With Flash Media Server, if `@setDataFrame` is the first argument, use `onMetaData` as the second argument; for the third argument, pass an instance of `Object` or `Array` that has the metadata set as properties. See the Flash Media Server documentation for a list of suggested property names. With `@clearDataFrame` as the first argument, use `onMetaData` as the second argument and no third argument.

See also

play()
client
Example
Flash Media Server The following example creates two `NetStream` objects. One is used to publish a live stream to the server, while the other subscribes to the stream.

      package {
           import flash.display.Sprite;
           import flash.net.NetConnection;
           import flash.net.NetStream;
           import flash.events.NetStatusEvent;
           import flash.media.Video;
           import flash.utils.setTimeout;

           public class TestExample extends Sprite
           {
             var nc:NetConnection = new NetConnection();
             var ns1:NetStream;
             var ns2:NetStream;
             var vid:Video = new Video(300,300);
             var obj:Object = new Object();

             public function TestExample() {
                nc.objectEncoding = 0;
                nc.addEventListener("netStatus", onNCStatus);
                nc.connect("rtmp://localhost/FlashVideoApp");
                addChild(vid);
             }

             function onNCStatus(event:NetStatusEvent):void {
               switch (event.info.code) {
                   case "NetConnection.Connect.Success":
                       trace("You've connected successfully");
                       ns1 = new NetStream(nc);
                       ns2 = new NetStream(nc);

                       ns1.client = new CustomClient();
                       ns1.publish("dummy", "live");

                       ns2.play("dummy");
                       ns2.client = new CustomClient();
                       vid.attachNetStream(ns2);
                       setTimeout(sendHello, 3000);
                       break;

                   case "NetStream.Publish.BadName":
                       trace("Please check the name of the publishing stream" );
                       break;
                }
             }
                  function sendHello():void {
                 ns1.send("myFunction", "hello");
             }
           }
         }

         class CustomClient {
            public function myFunction(event:String):void {
               trace(event);
            }
         }

Flash Media Server The following example creates metadata and adds it to a live stream:

      private function netStatusHandler(event:NetStatusEvent):void {
             switch (event.info.code) {
                case "NetStream.Publish.Start":
                    var metaData:Object = new Object();
                    metaData.title = "myStream";
                    metaData.width = 400;
                    metaData.height = 200;
                    ns.send("@setDataFrame", "onMetaData", metaData);
                    ns.attachCamera( Camera.getCamera() );
                    ns.attachAudio( Microphone.getMicrophone() );
                }
             }

Flash Media Server To respond to a data keyframe added to a video, the client needs to define an `onMetaData` event handler. The `onMetaData` event handler is not registered with `addEventListener()`, but instead is a callback function with the name `onMetaData`, for example:

      public function onMetaData(info:Object):void {
         trace("width: " + info.width);
         trace("height: " + info.height);
      }

Flash Media Server This example shows how to create a playlist on the server:

      // Create a NetStream for playing
      var my_ns:NetStream = new NetStream(my_nc);
      my_video.attachNetStream(my_ns);

      // Play the stream record1
      my_ns.play("record1", 0, -1, true);

      // Switch to the stream live1 and play for 5 seconds.
      // Since reset is false, live1 will start to play after record1 is done.
      my_ns.play("live1", -1 , 5, false);

Flash Media Server If the recorded video file contains only data messages, you can either play the video file at the speed at which it was originally recorded, or you can get the data messages all at once.

      //To play at normal speed
      var my_ns:NetStream = new NetStream(my_nc);
      my_ns.play("log", 0, -1);

      //To get the data messages all at once
      my_ns.play("log", 0, -1, 3);

togglePause | () | method |

`public function togglePause():void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Pauses or resumes playback of a stream. The first time you call this method, it pauses play; the next time, it resumes play. You could use this method to let users pause or resume playback by pressing a single button.

See also

close()
play()
pause()
resume()
Event Detail

asyncError | Event

Event Object Type: `flash.events.AsyncErrorEvent`
AsyncErrorEvent.type property = `flash.events.AsyncErrorEvent.ASYNC_ERROR`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code. This event is dispatched when a server calls a method on the client that is not defined.

The `AsyncErrorEvent.ASYNC_ERROR` constant defines the value of the `type` property of an `asyncError` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The object experiencing a network operation failure.
`error` | The error that triggered the event.

See also

NetStream.onPlayStatus
NetStream.onMetaData

ioError | Event |

Event Object Type: `flash.events.IOErrorEvent`
IOErrorEvent.type property = `flash.events.IOErrorEvent.IO_ERROR`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when an input or output error occurs that causes a network operation to fail.

Defines the value of the `type` property of an `ioError` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The network object experiencing the input/output error.
`text` | Text to be displayed as an error message.

netStatus | Event |

Event Object Type: `flash.events.NetStatusEvent`
NetStatusEvent.type property = `flash.events.NetStatusEvent.NET_STATUS`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when a NetStream object is reporting its status or error condition. The `netStatus` event contains an `info` property, which is an information object that contains specific information about the event, such as if a connection attempt succeeded or failed.

Defines the value of the `type` property of a `netStatus` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`info` | An object with properties that describe the object's status or error condition.
`target` | The NetConnection or NetStream object reporting its status.

See also

flash.events.NetStatusEvent.info

onCuePoint | Event |

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Establishes a listener to respond when an embedded cue point is reached while playing a video file. You can use the listener to trigger actions in your code when the video reaches a specific cue point, which lets you synchronize other actions in your application with video playback events. For information about video file formats supported by Flash Media Server, see the Flash Media Server documentation.

`onCuePoint` is actually a property of the `NetStream.client` object. It isn't an event, but is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the `addEventListener()` method, or any other EventDispatcher methods, to listen for, or process `onImageData` as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

- The object that the `client` property of a NetStream instance references.
- An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the `NetStream.play()` method, but before the video playhead has advanced.

The following types of cue points can be embedded in a video file:

- A navigation cue point specifies a keyframe within the video file and the cue point's `time` property corresponds to that exact keyframe. Navigation cue points are often used as bookmarks or entry points to let users navigate through the video file.
- An event cue point is specified by time, whether or not that time corresponds to a specific keyframe. An event cue point usually represents a time in the video when something happens that could be used to trigger other application events.

The `onCuePoint` event object has the following properties:

Property | Description
--- | ---
`name` | The name given to the cue point when it was embedded in the video file.
`parameters` | A associative array of name/value pair strings specified for this cue point. Any valid string can be used for the parameter name or value.
`time` | The time in seconds at which the cue point occurred in the video file during playback.
`type` | The type of cue point that was reached, either navigation or event.

You can define cue points in a video file when you first encode the file, or when you import a video clip in the Flash authoring tool by using the Video Import wizard.

The `onMetaData` event also retrieves information about the cue points in a video file. However the `onMetaData` event gets information about all of the cue points before the video begins playing. The `onCuePoint` event receives information about a single cue point at the time specified for that cue point during playback.

Generally, to have your code respond to a specific cue point at the time it occurs, use the `onCuePoint` event to trigger some action in your code.

You can use the list of cue points provided to the `onMetaData` event to let the user start playing the video at predefined points along the video stream. Pass the value of the cue point's `time` property to the `NetStream.seek()` method to play the video from that cue point.

See also

client
onMetaData

onImageData | Event |

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9.0.115.0

Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is playing. The image data can produce either JPEG, PNG or GIF content. Use the `flash.display.Loader.loadBytes()` method to load the byte array into a display object.

`onImageData` is actually a property of the `NetStream.client` object. It isn't an event, but is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the `addEventListener()` method, or any other EventDispatcher methods, to listen for, or process `onImageData` as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

- The object that the `client` property of a NetStream instance references.
- An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the `NetStream.play()` method, but before the video playhead has advanced.

The onImageData event object contains the image data as a byte array sent through an AMF0 data channel.

Example
The code in this example uses the `Netstream.client` property to handle the callback functions for `onTextData` and `onImageData`. The `onImageDataHandler()` function uses the onImageData event object `imageData` to store the byte array. And, the `onTextDataHandler()` function uses the onTextData event object `textData` to store the pieces of text data (each piece of data is a property of the `textData` object).

You need to substitute a real location to a media file with text or image metadata for the location `"yourURL"` in the code.

You can also handle image and text data using a custom class. See the article Handling metadata and cue points in Flash video for more information and examples.

    package {
        import flash.display.*;
        import flash.net.*;
        import flash.media.*;
        import flash.system.*;
        import flash.events.*;

            public class OnTextDataExample extends Sprite {

                public function OnTextDataExample():void {

                    var customClient:Object = new Object();
                    customClient.onImageData = onImageDataHandler;
                    customClient.onTextData = onTextDataHandler;

                    var my_nc:NetConnection = new NetConnection();
                    my_nc.connect(null);
                    var my_ns:NetStream = new NetStream(my_nc);
                    my_ns.play("yourURL");
                    my_ns.client = customClient;

                    var my_video:Video = new Video();
                    my_video.attachNetStream(my_ns);
                    addChild(my_video);

                }

                public function onImageDataHandler(imageData:Object):void {

                    trace("imageData length: " + imageData.data.length);
                    var imageloader:Loader = new Loader();
                    imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object.
                    addChild(imageloader);
                }

                public function onTextDataHandler(textData:Object):void {

                    trace("--- textData properties ----");
                    var key:String;

                    for (key in textData) {
                        trace(key + ": " + textData[key]);
                    }
                }

            }

    }

See also

NetConnection
flash.display.Loader.loadBytes()
client
asyncError
play()
onTextData

onMetaData | Event |

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. For information about video file formats supported by Flash Media Server, see the Flash Media Server documentation.

`onMetaData` is actually a property of the `NetStream.client` object. It isn't an event, but is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description and the `NetStream.client` property. You cannot use the `addEventListener()` method, or any other EventDispatcher methods, to listen for or process `onMetaData` as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

- The object that the `client` property of a NetStream instance references.
- An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

The Flash Video Exporter utility (version 1.1 or later) embeds a video's duration, creation date, data rates, and other information into the video file itself. Different video encoders embed different sets of meta data.

The associated event listener is triggered after a call to the `NetStream.play()` method, but before the video playhead has advanced.

In many cases, the duration value embedded in stream metadata approximates the actual duration but is not exact. In other words, it does not always match the value of the `NetStream.time` property when the playhead is at the end of the video stream.

The event object passed to the onMetaData event handler contains one property for each piece of data.

See also

NetConnection
client
asyncError
onCuePoint
play()
time

onPlayStatus | Event |

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Establishes a listener to respond when a NetStream object has completely played a stream. The associated event object provides information in addition to what's returned by the `netStatus` event. You can use this property to trigger actions in your code when a NetStream object has switched from one stream to another stream in a playlist (as indicated by the information object `NetStream.Play.Switch`) or when a NetStream object has played to the end (as indicated by the information object `NetStream.Play.Complete`).

`onPlayStaus` is actually a property of the `NetStream.client` object. It isn't an event, but is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the `addEventListener()` method, or any other EventDispatcher methods, to listen for, or process `onImageData` as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

- The object that the `client` property of a NetStream instance references.
- An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

This event can return an information object with the following properties:

Code property | Level property | Meaning
--- | --- | ---
`NetStream.Play.Switch` | `"status"` | The subscriber is switching from one stream to another in a playlist.
`NetStream.Play.Complete` | `"status"` | Playback has completed.

See also

client
flash.events.NetStatusEvent.NET_STATUS
asyncError
onMetaData
onCuePoint

onTextData | Event |

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9.0.115.0

Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. The text data is in UTF-8 format and can contain information about formatting based on the 3GP timed text specification.

`onTextData` is actually a property of the `NetStream.client` object. It isn't an event, but is listed in the Events section because it responds to a data event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class description. You cannot use the `addEventListener()` method, or any other EventDispatcher methods, to listen for, or process `onImageData` as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

- The object that the `client` property of a NetStream instance references.
- An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream and define your event handler in the subclass or make the subclass dynamic and add the event handler function to an instance of the subclass.

The associated event listener is triggered after a call to the `NetStream.play()` method, but before the video playhead has advanced.

The onTextData event object contains one property for each piece of text data.

Example
The code in this example uses the `Netstream.client` property to handle the callback functions for `onTextData` and `onImageData`. The `onImageDataHandler()` function uses the onImageData event object `imageData` to store the byte array. And, the `onTextDataHandler()` function uses the onTextData event object `textData` to store the pieces of text data (each piece of data is a property of the `textData` object).

You need to substitute a real location to a media file with text or image metadata for the location `"yourURL"` in the code.

You can also handle image and text data using a custom class. See the article Handling metadata and cue points in Flash video for more information and examples.

    package {
        import flash.display.*;
        import flash.net.*;
        import flash.media.*;
        import flash.system.*;
        import flash.events.*;

            public class OnTextDataExample extends Sprite {

                public function OnTextDataExample():void {

                    var customClient:Object = new Object();
                    customClient.onImageData = onImageDataHandler;
                    customClient.onTextData = onTextDataHandler;

                    var my_nc:NetConnection = new NetConnection();
                    my_nc.connect(null);
                    var my_ns:NetStream = new NetStream(my_nc);
                    my_ns.play("yourURL");
                    my_ns.client = customClient;

                    var my_video:Video = new Video();
                    my_video.attachNetStream(my_ns);
                    addChild(my_video);

                }

                public function onImageDataHandler(imageData:Object):void {

                    trace("imageData length: " + imageData.data.length);
                    var imageloader:Loader = new Loader();
                    imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object.
                    addChild(imageloader);
                }

                public function onTextDataHandler(textData:Object):void {

                    trace("--- textData properties ----");
                    var key:String;

                    for (key in textData) {
                        trace(key + ": " + textData[key]);
                    }
                }

            }

    }

See also

NetConnection
client
asyncError
play()
onImageData
Constant Detail

DIRECT_CONNECTIONS | Constant

`public static const DIRECT_CONNECTIONS:String = "directConnections"`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

The `DIRECT_CONNECTIONS` string is a static object used as a parameter to the constructor for a NetStream. This is how a player-server would create a NetStream for the purposes of publishing audio and video to player-clients.

Examples How to use examples
NetConnectionExample.as
The following example uses a Video object with the NetConnection and NetStream classes to load and play an FLV file. To run this example, you need an FLV file whose name and location match the variable passed to `videoURL`; in this case, an FLV file called Video.flv that is in the same directory as the SWF file.

In this example, the code that creates the Video and NetStream objects and calls the `Video.attachNetStream()` and `NetStream.play()` methods is placed in a handler function. The handler is called only if the attempt to connect to the NetConnection object is successful; that is, when the `netStatus` event returns an `info` object with a `code` property that indicates success. It is recommended that you wait for a successful connection before you call `NetStream.play()`.

    package {
        import flash.display.Sprite;
        import flash.events.NetStatusEvent;
        import flash.events.SecurityErrorEvent;
        import flash.media.Video;
        import flash.net.NetConnection;
        import flash.net.NetStream;
        import flash.events.Event;

        public class NetConnectionExample extends Sprite {
            private var videoURL:String = "Video.flv";
            private var connection:NetConnection;
            private var stream:NetStream;

            public function NetConnectionExample() {
                connection = new NetConnection();
                connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
                connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
                connection.connect(null);
            }

            private function netStatusHandler(event:NetStatusEvent):void {
                switch (event.info.code) {
                    case "NetConnection.Connect.Success":
                        connectStream();
                        break;
                    case "NetStream.Play.StreamNotFound":
                        trace("Stream not found: " + videoURL);
                        break;
                }
            }

            private function securityErrorHandler(event:SecurityErrorEvent):void {
                trace("securityErrorHandler: " + event);
            }

            private function connectStream():void {
                var stream:NetStream = new NetStream(connection);
                stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
                stream.client = new CustomClient();
                var video:Video = new Video();
                video.attachNetStream(stream);
                stream.play(videoURL);
                addChild(video);
            }
        }
    }

    class CustomClient {
        public function onMetaData(info:Object):void {
            trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate);
        }
        public function onCuePoint(info:Object):void {
            trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type);
        }
    }

Submit Feedback on LiveDocs
© 2004-2008 Adobe Systems Incorporated. All rights reserved.
Tue May 20 2008, 04:02 AM -07:00