Packageflash.net
Classpublic class NetStream
InheritanceNetStream Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: 

The NetStream class opens a one-way streaming channel over a NetConnection.

Use the NetStream class to do the following:

Note:You cannot play and publish a stream over the same NetStream object.

Adobe AIR and Flash Player 9.0.115.0 and later versions support files derived from the standard MPEG-4 container format. These files include F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2 if they contain H.264 video, HEAAC v2 encoded audio, or both. H.264 delivers higher quality video at lower bit rates when compared to the same encoding profile in Sorenson or On2. AAC is a standard audio format defined in the MPEG-4 video standard. HE-AAC v2 is an extension of AAC that uses Spectral Band Replication (SBR) and Parametric Stereo (PS) techniques to increase coding efficiency at low bit rates.

For information about supported codecs and file formats, see the following:

Receiving data from a Flash Media Server stream, progressive F4V file, or progressive FLV file

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

Wait to receive a NetGroup.Neighbor.Connect event before you use the object replication, direct routing, or posting APIs.

Note: To send data through an audio file, like an mp3 file, use the Sound class to associate the audio file with a Sound object. Then, use the Sound.id3 property to read metadata from the sound file.

Support for H.264 encoded video in AIR for iOS

For H.264 video, AIR 3.0 (and later) for iOS supports a subset of the full NetStream API. The following table lists NetStream members for playback that are not supported in AIR for iOS:

Unsupported propertiesUnsupported methodsUnsupported events
bufferTimeappendBytes()onCuePoint (works only with FLV files)
bufferLengthappendBytesAction()onImageData
backBufferTimestep()onSeekPoint
backBufferLengthonTextData
bufferTimeMaxonXMPData
bytesLoadeddrmError
currentFPSdrmStatus
inBufferSeekonDRMContentData
infodrmAuthenticate
liveDelayDRM.encryptedFLV status event code
maxPauseBufferTime
soundTransform
All properties describing RTMFP connections

For additional information on using AIR for iOS, see the NetStream.play() method.

View the examples.

See also

flash.media.Video
flash.net.NetConnection
appendBytes()
play()
publish()
send()
onImageData
onMetaData


Public Properties
 PropertyDefined by
  audioReliable : Boolean
For RTMFP connections, specifies whether audio is sent with full reliability.
NetStream
  audioSampleAccess : Boolean
For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream.
NetStream
  backBufferLength : Number
[read-only] The number of seconds of previously displayed data that currently cached for rewinding and playback.
NetStream
  backBufferTime : Number
Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds.
NetStream
  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
  bufferTimeMax : Number
Specifies a maximum buffer length for live streaming content, in seconds.
NetStream
  bytesLoaded : uint
[read-only] The number of bytes of data that have been loaded into the application.
NetStream
  bytesTotal : uint
[read-only] The total size in bytes of the file being loaded into the application.
NetStream
  checkPolicyFile : Boolean
Specifies whether the application tries to download a cross-domain 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 F4V/FLV file data.
NetStream
 Inheritedconstructor : 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
  dataReliable : Boolean
For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability.
NetStream
  farID : String
[read-only] For RTMFP connections, the identifier of the far end that is connected to this NetStream instance.
NetStream
  farNonce : String
[read-only] For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection.
NetStream
  inBufferSeek : Boolean
Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE).
NetStream
  info : NetStreamInfo
[read-only] Returns a NetStreamInfo object whose properties contain statistics about the quality of service.
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, in seconds.
NetStream
  multicastAvailabilitySendToAll : Boolean
For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are sent to all peers or to just one peer.
NetStream
  multicastAvailabilityUpdatePeriod : Number
For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that the local node has new peer-to-peer multicast media fragments available.
NetStream
  multicastFetchPeriod : Number
For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer multicast media fragment is available and when it tries to fetch it from a peer.
NetStream
  multicastInfo : NetStreamMulticastInfo
[read-only] For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service.
NetStream
  multicastPushNeighborLimit : Number
For RTMFP connections, specifies the maximum number of peers to which to proactively push multicast media.
NetStream
  multicastRelayMarginDuration : Number
For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains available to send to peers that request it beyond a specified duration.
NetStream
  multicastWindowDuration : Number
For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly window.
NetStream
  nearNonce : String
[read-only] For RTMFP and RTMPE connections, 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] An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance.
NetStream
 Inheritedprototype : 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
  useHardwareDecoder : Boolean
Specifies whether to use hardware accelerated decoding on the stream.
NetStream
  useJitterBuffer : Boolean
Minimize latency for live un-buffered streaming (bufferTime = 0).
NetStream
  videoReliable : Boolean
For RTMFP connections, specifies whether video is sent with full reliability.
NetStream
  videoSampleAccess : Boolean
For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream.
NetStream
  videoStreamSettings : VideoStreamSettings
NetStream
Public Methods
 MethodDefined by
  
NetStream(connection:NetConnection, peerID:String = "connectToFMS")
Creates a stream that you can use to play media files and send data over a NetConnection object.
NetStream
 Inherited
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
  
Passes a ByteArray into a NetStream for playout.
NetStream
  
appendBytesAction(netStreamAppendBytesAction:String):void
Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag.
NetStream
  
attach(connection:NetConnection):void
Attaches a stream to a new NetConnection object.
NetStream
  
Attaches an audio stream to a 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
  
Stops playing all data on the stream, sets the time property to 0, and makes the stream available for another use.
NetStream
 Inherited
Dispatches an event into the event flow.
EventDispatcher
  
Releases all the resources held by the NetStream object.
NetStream
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
Invoked when a peer-publishing stream matches a peer-subscribing stream.
NetStream
  
Pauses playback of a video stream.
NetStream
  
play(... arguments):void
Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server.
NetStream
  
Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected.
NetStream
  
Extracts any DRM metadata from a locally stored media file.
NetStream
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
  
publish(name:String = null, type:String = null):void
Sends streaming audio, video, and data messages from a client to Flash Media Server, optionally recording the stream during transmission.
NetStream
  
Specifies whether incoming audio plays on the stream.
NetStream
  
Specifies whether incoming video plays on the stream.
NetStream
  
Specifies the frame rate for incoming video.
NetStream
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
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
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
step(frames:int):void
Steps forward or back the specified number of frames, relative to the currently displayed frame.
NetStream
  
Pauses or resumes playback of a stream.
NetStream
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 EventSummaryDefined by
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
   Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.NetStream
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
   Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted content that requires a user credential for authentication before playing.NetStream
   Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted file, encounters a DRM-related error.NetStream
   Dispatched when the digital rights management (DRM) encrypted content begins playing (when the user is authenticated and authorized to play the content).NetStream
   Dispatched when an input or output error occurs that causes a network operation to fail.NetStream
   Dispatched when playing video content and certain type of messages are processed.NetStream
   Dispatched when a NetStream object is reporting its status or error condition.NetStream
   Establishes a listener to respond when an embedded cue point is reached while playing a video file.NetStream
   Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file.NetStream
   Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is playing.NetStream
   Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played.NetStream
   Establishes a listener to respond when a NetStream object has completely played a stream.NetStream
   Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable point (for example, a video key frame).NetStream
   Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing.NetStream
   Establishes a listener to respond when Flash Player receives information specific to Adobe Extensible Metadata Platform (XMP) embedded in the video being played.NetStream
   Dispatched when the application attempts to play content encrypted with digital rights management (DRM), by invoking the NetStream.play() method.NetStream
Public Constants
 ConstantDefined by
  CONNECT_TO_FMS : String = "connectToFMS"
[static] A static object used as a parameter to the constructor for a NetStream instance.
NetStream
  DIRECT_CONNECTIONS : String = "directConnections"
[static] Creates a peer-to-peer publisher connection.
NetStream
Property detail
audioReliableproperty
audioReliable:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether audio is sent with full reliability. When TRUE, all audio transmitted over this NetStream is fully reliable. When FALSE, the audio transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. You can use the FALSE value to reduce latency at the expense of audio quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get audioReliable():Boolean
    public function set audioReliable(value:Boolean):void

See also

audioSampleAccessproperty 
audioSampleAccess:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream. When FALSE, subscriber attempts to capture the audio stream show permission errors.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get audioSampleAccess():Boolean
    public function set audioSampleAccess(value:Boolean):void

See also

backBufferLengthproperty 
backBufferLength:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

The number of seconds of previously displayed data that currently cached for rewinding and playback.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

This property is available only when data is streaming from Flash Media Server 3.5.3 or higher; for more information on Flash Media Server, see the class description.

To specify how much previously displayed data is cached, use the Netstream.backBufferTime property.

To prevent data from being cached, set the Netstream.inBufferSeek property to FALSE.

Implementation
    public function get backBufferLength():Number

See also

backBufferTimeproperty 
backBufferTime:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds. The default value is 30 seconds for desktop applications and 3 seconds for mobile applications.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

This property is available only when data is streaming from Flash Media Server version 3.5.3 or later; for more information on Flash Media Server, see the class description.

Using this property improves performance for rewind operations, as data that has already been displayed isn't retrieved from the server again. Instead, the stream begins replaying from the buffer. During playback, data continues streaming from the server until the buffer is full.

If the rewind position is farther back than the data in the cache, the buffer is flushed; the data then starts streaming from the server at the requested position.

To use this property set the Netstream.inBufferSeek property to TRUE.

Implementation
    public function get backBufferTime():Number
    public function set backBufferTime(value:Number):void

See also

bufferLengthproperty 
bufferLength:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get bufferLength():Number

See also

bufferTimeproperty 
bufferTime:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: 

Specifies how long to buffer messages before starting to display the stream.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

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.

To play a server-side playlist, set bufferTime to at least 1 second. If you experience playback issues, increase the length of bufferTime.

Recorded content To avoid distortion when streaming pre-recorded (not live) content, do not set the value of Netstream.bufferTime to 0. By default, the application 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.

Live content When streaming live content, set the bufferTime property to 0.

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. 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. 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 the application starts dropping frames. On a high-speed connection, buffer time is not a concern; data is sent almost as quickly as the application can buffer it. On a slow connection, however, there can be a significant difference between how fast the application buffers the data and how fast it is sent to the client.

For a subscribing stream, bufferTime specifies how long to buffer incoming data before starting to display the stream.

When a recorded stream is played, if bufferTime is 0, 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

bufferTimeMaxproperty 
bufferTimeMax:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

Specifies a maximum buffer length for live streaming content, in seconds. The default value is 0. Buffer length can grow over time due to networking and device issues (such as clock drift between sender and receiver). Set this property to cap the buffer length for live applications such as meetings and surveillance.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

When bufferTimeMax > 0 and bufferLength >= bufferTimeMax, audio plays faster until bufferLength reaches bufferTime. If a live stream is video-only, video plays faster until bufferLength reaches bufferTime.

Depending on how much playback is lagging (the difference between bufferLength and bufferTime), Flash Player controls the rate of catch-up between 1.5% and 6.25%. If the stream contains audio, faster playback is achieved by frequency domain downsampling which minimizes audible distortion.

Set the bufferTimeMax property to enable live buffered stream catch-up in the following cases:

Implementation
    public function get bufferTimeMax():Number
    public function set bufferTimeMax(value:Number):void

See also

bytesLoadedproperty 
bytesLoaded:uint  [read-only]

Language version: ActionScript 3.0
Runtime version: 

The number of bytes of data that have been loaded into the application. 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.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get bytesLoaded():uint

See also

bytesTotalproperty 
bytesTotal:uint  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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

Implementation
    public function get bytesTotal():uint

See also

checkPolicyFileproperty 
checkPolicyFile:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: 

Specifies whether the application tries to download a cross-domain policy file from the loaded video file's server before beginning to load the video file. Use this property for progressive video download, and to load files that are outside the calling SWF file's own domain. This property is ignored when you are using RTMP.

Set this property to true to call BitmapData.draw() on a video file loaded from a domain outside that of the calling SWF. The BitmapData.draw() method provides pixel-level access to the video. If you call BitmapData.draw() without setting the checkPolicyFile property to true at loading time, you can get a SecurityError exception because the required policy file was not downloaded.

Do not set this property to true unless you want pixel-level access to the video you are loading. Checking for a policy file consumes network bandwidth and can delay the start of your download.

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

  1. The application considers policy files that have already been downloaded.
  2. The application tries to download any pending policy files specified in calls to the Security.loadPolicyFile() method.
  3. The application 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 or Adobe AIR 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 code's file to access the video, through one or more <allow-access-from> tags.

If you set checkPolicyFile to true, the application 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 the application throws a SecurityError exception.

Be careful with checkPolicyFile if you are downloading a file from a URL that uses server-side HTTP redirects. The application 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 "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security.

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

See also

clientproperty 
client:Object  [read-write]

Language version: ActionScript 3.0
Runtime version: 

Specifies the object on which callback methods are invoked to handle streaming or F4V/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(), onSeekPoint(), onTextData(), and onXMPData().

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

currentFPSproperty 
currentFPS:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get currentFPS():Number
dataReliableproperty 
dataReliable:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability. When TRUE, NetStream.send() calls that are transmitted over this NetStream are fully reliable. When FALSE, NetStream.send() calls are not transmitted with full reliability, but instead are retransmitted for a limited time and then dropped. You can set this value to FALSE to reduce latency at the expense of data quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get dataReliable():Boolean
    public function set dataReliable(value:Boolean):void

See also

farIDproperty 
farID:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

For RTMFP connections, the identifier of the far end that is connected to this NetStream instance.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get farID():String
farNonceproperty 
farNonce:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection. This value appears to the other end of the stream as its nearNonce value.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get farNonce():String
inBufferSeekproperty 
inBufferSeek:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE). The default value is FALSE.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Flash Media Server 3.5.3 and Flash Player 10.1 work together to support smart seeking. Smart seeking uses back and forward buffers to seek without requesting data from the server. Standard seeking flushes buffered data and asks the server to send new data based on the seek time.

Call NetStream.step() to step forward and backward a specified number of frames. Call NetStream.seek() to seek forward and backward a specified number of seconds.

Smart seeking reduces server load and improves seeking performance. Set inBufferSeek=true and call step() and seek() to create:

When inBufferSeek=true and a call to NetStream.seek() is successful, the NetStatusEvent info.description property contains the string "client-inBufferSeek".

When a call to NetStream.step() is successful, the NetStatusEvent info.code property contains the string "NetStream.Step.Notify".

Implementation
    public function get inBufferSeek():Boolean
    public function set inBufferSeek(value:Boolean):void

See also

infoproperty 
info:NetStreamInfo  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Returns a NetStreamInfo object whose properties contain statistics about the quality of service. The object is a snapshot of the current state.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get info():NetStreamInfo

See also

liveDelayproperty 
liveDelay:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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).

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

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
maxPauseBufferTimeproperty 
maxPauseBufferTime:Number  [read-write]

Runtime version: AIR 1.5

Specifies how long to buffer messages during pause mode, in seconds. This property can be used to limit how much buffering is done during pause mode. As soon as the value of NetStream.bufferLength reaches this limit, it stops buffering.

If this value is not set, it defaults the limit to 60 seconds or twice the value of NetStream.bufferTime on each pause, whichever is higher.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get maxPauseBufferTime():Number
    public function set maxPauseBufferTime(value:Number):void

See also

multicastAvailabilitySendToAllproperty 
multicastAvailabilitySendToAll:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are sent to all peers or to just one peer. A value of TRUE specifies that the messages are sent to all peers once per specified interval. A value of FALSE specifies that the messages are sent to just one peer per specified interval. The interval is determined by the multicastAvailabilityUpdatePeriod property.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastAvailabilitySendToAll():Boolean
    public function set multicastAvailabilitySendToAll(value:Boolean):void

See also

multicastAvailabilityUpdatePeriodproperty 
multicastAvailabilityUpdatePeriod:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that the local node has new peer-to-peer multicast media fragments available. Larger values can increase batching efficiency and reduce control overhead, but they can lower quality on the receiving end by reducing the amount of time available to retrieve fragments before they are out-of-window. Lower values can reduce latency and improve quality, but they increase control overhead.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastAvailabilityUpdatePeriod():Number
    public function set multicastAvailabilityUpdatePeriod(value:Number):void

See also

multicastFetchPeriodproperty 
multicastFetchPeriod:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer multicast media fragment is available and when it tries to fetch it from a peer. This value gives an opportunity for the fragment to be proactively pushed to the local node before a fetch from a peer is attempted. It also allows for more than one peer to announce availability of the fragment, so the fetch load can be spread among multiple peers.

Larger values can improve load balancing and fairness in the peer-to-peer mesh, but reduce the available multicastWindowDuration and increase latency. Smaller values can reduce latency when fetching is required, but might increase duplicate data reception and reduce peer-to-peer mesh load balance.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastFetchPeriod():Number
    public function set multicastFetchPeriod(value:Number):void

See also

multicastInfoproperty 
multicastInfo:NetStreamMulticastInfo  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service. The object is a snapshot of the current state.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastInfo():NetStreamMulticastInfo

See also

multicastPushNeighborLimitproperty 
multicastPushNeighborLimit:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies the maximum number of peers to which to proactively push multicast media.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastPushNeighborLimit():Number
    public function set multicastPushNeighborLimit(value:Number):void
multicastRelayMarginDurationproperty 
multicastRelayMarginDuration:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains available to send to peers that request it beyond a specified duration. The duration is specified by the multicastWindowDuration property.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastRelayMarginDuration():Number
    public function set multicastRelayMarginDuration(value:Number):void

See also

multicastWindowDurationproperty 
multicastWindowDuration:Number  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly window. Shorter values reduce latency but may reduce quality by not allowing enough time to obtain all of the fragments. Conversely, larger values may increase quality by providing more time to obtain all of the fragments, with a corresponding increase in latency.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get multicastWindowDuration():Number
    public function set multicastWindowDuration(value:Number):void

See also

nearNonceproperty 
nearNonce:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

For RTMFP and RTMPE connections, a value chosen substantially by this end of the stream, unique to this connection. This value appears to the other end of the stream as its farNonce value.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get nearNonce():String
objectEncodingproperty 
objectEncoding:uint  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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, the application throws an exception.

Implementation
    public function get objectEncoding():uint

See also

peerStreamsproperty 
peerStreams:Array  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.5

An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance.

Implementation
    public function get peerStreams():Array
soundTransformproperty 
soundTransform:SoundTransform  [read-write]

Language version: ActionScript 3.0
Runtime version: 

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

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

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

See also

timeproperty 
time:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: 

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 the time property stops advancing. When the server begins sending data again, the value continues to advance from the point at which it stopped (when the server stopped sending data).

The value of time continues to advance 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

useHardwareDecoderproperty 
useHardwareDecoder:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 3

Specifies whether to use hardware accelerated decoding on the stream.

Note: You cannot set this property during video playback. You must set it before you call NetStream.play().

The default value is true.

Implementation
    public function get useHardwareDecoder():Boolean
    public function set useHardwareDecoder(value:Boolean):void

See also

useJitterBufferproperty 
useJitterBuffer:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 3.3

Minimize latency for live un-buffered streaming (bufferTime = 0). Instead of conservative push-based catchup mechanism, audio messages are placed in an adaptive jitter buffer. When audio is needed by speaker device, messages are popped from jitter buffer, decoded, and played back. Speex and G.711 always use this pull-based approach, regardless of this settings (useJitterBuffer returns true for Speex/G.711). When enabled in un-buffered mode, all the codecs use jitter buffer, such as Speex, G.711, Nellymoser, MP3 and AAC. This property has no effect in buffered mode (bufferTime > 0), and thus useJitterBuffer returns false.

Implementation
    public function get useJitterBuffer():Boolean
    public function set useJitterBuffer(value:Boolean):void
videoReliableproperty 
videoReliable:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether video is sent with full reliability. When TRUE, all video transmitted over this NetStream is fully reliable. When FALSE, the video transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. You can use the FALSE value to reduce latency at the expense of video quality.

If you try to set this property to FALSE on a network protocol that does not support partial reliability, the attempt is ignored and the property is set to TRUE.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get videoReliable():Boolean
    public function set videoReliable(value:Boolean):void

See also

videoSampleAccessproperty 
videoSampleAccess:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 2

For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream. When FALSE, subscriber attempts to capture the video stream show permission errors.

Note: This property is not supported for H.264 video in AIR 3.0 for iOS.

Implementation
    public function get videoSampleAccess():Boolean
    public function set videoSampleAccess(value:Boolean):void

See also

videoStreamSettingsproperty 
videoStreamSettings:VideoStreamSettings  [read-write]Implementation
    public function get videoStreamSettings():VideoStreamSettings
    public function set videoStreamSettings(value:VideoStreamSettings):void
Constructor detail
NetStream()constructor
public function NetStream(connection:NetConnection, peerID:String = "connectToFMS")

Language version: ActionScript 3.0
Runtime version: 

Creates a stream that you can use to play media files and send data over a NetConnection object.

It is considered invalid to not handle a NetStream object's netStatus event. To avoid errors, register a listener for the netStatus after creating the NetStream object and before calling its play() method.

Parameters
connection:NetConnection — A NetConnection object.
 
peerID:String (default = "connectToFMS") — This optional parameter is available in Flash Player 10 and later, for use with RTMFP connections. (If the value of the NetConnection.protocol property is not "rtmfp", this parameter is ignored.) Use one of the following values:
  • To connect to Flash Media Server, specify NetStream.CONNECT_TO_FMS.
  • To publish directly to peers, specify NetStream.DIRECT_CONNECTIONS.
  • To play directly from a specific peer, specify that peer's identity (see NetConnection.nearID and NetStream.farID).
  • (Flash Player 10.1 or AIR 2 or later) To publish or play a stream in a peer-to-peer multicast group, specify a groupspec string (see the GroupSpecifier class).

In most cases, a groupspec has the potential to use the network uplink on the local system. In this case, the user is asked for permission to use the computer's network resources. If the user allows this use, a NetStream.Connect.Success NetStatusEvent is sent to the NetConnection's event listener. If the user denies permission, a NetStream.Connect.Rejected event is sent. When specifying a groupspec, until a NetStream.Connect.Success event is received, it is an error to use any method of the NetStream object, and an exception is raised.

If you include this parameter in your constructor statement but pass a value of null, the value is set to "connectToFMS".


Throws
ArgumentError — The NetConnection instance is not connected.

See also


Example
The following code shows a connection to download and display, progressively, a video assigned to the variable videoURL:
var my_video:Video = new Video();
addChild(my_video);
var my_nc:NetConnection = new NetConnection();
my_nc.connect(null);
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachNetStream(my_ns);
my_ns.play(videoURL);

The following code shows a connection to stream and display a video (assigned to the variable videoURL) on a remote Flash Media Server instance specified in the connect() command:
var my_video:Video = new Video();
addChild(my_video);
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://www.yourfmsserver.com/someappname");
var my_ns:NetStream = new NetStream(my_nc, NetStream.CONNECT_TO_FMS);
my_video.attachNetStream(my_ns);
my_ns.play(videoURL);

Method detail
appendBytes()method
public function appendBytes(bytes:ByteArray):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Passes a ByteArray into a NetStream for playout. Call this method on a NetStream in "Data Generation Mode". To put a NetStream into Data Generation Mode, call NetStream.play(null) on a NetStream created on a NetConnection connected to null. Calling appendBytes() on a NetStream that isn't in Data Generation Mode is an error and raises an exception.

Note: This method is not supported for H.264 video in AIR 3.0 for iOS.

The byte parser understands an FLV file with a header. After the header is parsed, appendBytes() expects all future calls to be continuations of the same real or virtual file. Another header is not expected unless appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) is called.

A NetStream object has two buffers: the FIFO from appendBytes() to the NetStream, and the playout buffer. The FIFO is the partial-FLV-tag reassembly buffer and contains no more than one incomplete FLV tag. Calls to NetStream.seek() flush both buffers. After a call to seek(), call appendBytesAction() to reset the timescale to begin at the timestamp of the next appended message.

Each call to appendBytes() adds bytes into the FIFO until an FLV tag is complete. When an FLV tag is complete, it moves to the playout buffer. A call to appendBytes() can write multiple FLV tags. The first bytes complete an existing FLV tag (which moves to the playout buffer). Complete FLV tags move to the playout buffer. Remaining bytes that don’t form a complete FLV tag go into the FIFO. Bytes in the FIFO are either completed by a call to appendBytes() or flushed by a call to appendBytesAction() with the RESET_SEEK or RESET_BEGIN argument.

Note: The byte parser may not be able to completely decode a call to appendBytes() until a subsequent call to appendBytes() is made.

Parameters
bytes:ByteArray

See also

appendBytesAction()method 
public function appendBytesAction(netStreamAppendBytesAction:String):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag.

Note: This method is not supported for H.264 video in AIR 3.0 for iOS.

Calls to NetStream.seek() flush the NetStream buffers. The byte parser remains in flushing mode until you call appendBytesAction() and pass the RESET_BEGIN or RESET_SEEK argument. Capture the "NetStream.Seek.Notify" event to call appendBytesAction() after a seek. A new file header can support playlists and seeking without calling NetStream.seek().

You can also call this method to reset the byte counter for the onSeekPoint()) callback.

Parameters
netStreamAppendBytesAction:String

See also

attach()method 
public function attach(connection:NetConnection):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Attaches a stream to a new NetConnection object. Call this method to attach a NetStream to a new NetConnection object after a connection has dropped and been reconnected. Flash Player and AIR resume streaming from the playback point when the connection was lost.You can also use this method to implement load balancing.

This method requires Flash Media Server version 3.5.3 or later.

To use this method to implement stream reconnection, see the Flash Media Server 3.5.3 documentation.

To use this method to implement load balancing, do the following:

  1. Attach a connected stream to a NetConnection object on another server.
  2. After the stream is successfully attached to the new connection, call NetConnection.close() on the prior connection to prevent data leaks.
  3. Call NetStream.play2() and set the value of NetStreamPlayOptions.transition to RESUME. Set the rest of the NetStreamPlayOptions properties to the same values you used when you originally called NetStream.play() or NetStream.play2() to start the stream.
Parameters
connection:NetConnection

See also

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

Language version: ActionScript 3.0
Runtime version: 

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

Use this method with Flash Media Server to send live audio to the server. Call this method before or after you call the publish() method.

Set the Microphone.rate property to match the rate of the sound capture device. Call setSilenceLevel() to set the silence level threshold. To control the sound properties (volume and panning) of the audio stream, use the Microphone.soundTransform property.

     var nc:NetConnection = new NetConnection();
     nc.connect("rtmp://server.domain.com/app");
     var ns:NetStream = new NetStream(nc);
     
     var live_mic:Microphone = Microphone.get();
     live_mic.rate = 8;
     live_mic.setSilenceLevel(20,200);
     
     var soundTrans:SoundTransform = new SoundTransform();
     soundTrans.volume = 6;
     live_mic.soundTransform = soundTrans;
     
     ns.attachAudio(live_mic);
     ns.publish("mic_stream","live")
     

To hear the audio, call the NetStream.play() method and call DisplayObjectContainer.addChild() to route the audio to an object on the display list.

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

See also

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

Language version: ActionScript 3.0
Runtime version: 

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 the video message. By repeatedly calling attachCamera() with a positive value for snapshotMilliseconds, the sequence of alternating snapshots and trailers creates 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:

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, the application 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, the application captures all video until you pass a value of null to attachCamera.
  • If you pass 0, the application captures only a single video frame. Use this value to transmit "snapshots" within a preexisting stream. Flash Player or AIR interprets invalid, negative, or nonnumeric arguments as 0.
  • If you pass a positive number, the application 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
Runtime version: 

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 the application deletes the local copy of the file that it creates, a copy might persist in the 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 subscribing stream. Please note that:

See also

dispose()method 
public function dispose():void

Language version: ActionScript 3.0
Runtime version: AIR 3.0

Releases all the resources held by the NetStream object.

The dispose() method is similar to the close method. The main difference between the two methods is that dispose() releases the memory used to display the current video frame. If that frame is currently displayed on screen, the display will go blank. The close() method does not blank the display because it does not release this memory.

onPeerConnect()method 
public function onPeerConnect(subscriber:NetStream):Boolean

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Invoked when a peer-publishing stream matches a peer-subscribing stream. Before the subscriber is connected to the publisher, call this method to allow the ActionScript code fine access control for peer-to-peer publishing. The following code shows an example of how to create a callback function for this method:

     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, 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
Runtime version: 

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. This behavior is called "smart pause". Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming playback, which often caused a delay.

Note: For backwards compatibility, the "NetStream.Buffer.Flush" event (see the NetStatusEvent.info property) still fires, although the server does not flush the buffer.

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

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

Language version: ActionScript 3.0
Runtime version: 

Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server. Dispatches a NetStatusEvent object to report status and error messages.

For information about supported codecs and file formats, see the following:

Workflow for playing a file or live stream

  1. Create a Video object that will display the video and call addChild() to add it to the stage.
  2. Create a NetConnection object and call NetConnection.connect().

    To play a file from a local directory or web server, pass null.

    To play a recorded file or live stream from Flash Media Server, pass the URI of a Flash Media Server application.

  3. Call the NetConnection object's addEventListener() method to listen for the netStatus (NetStatusEvent.NET_STATUS) event.
  4. On "NetConnection.Connect.Success", create a NetStream object and pass the NetConnection object to the constructor.
  5. Call the Viceo object's attachNetStream() method and pass the NetStream object.
  6. Call the NetStream object's play() method.

    To play a live stream, pass the stream name passed to the NetStream.publish() method.

    To play a recorded file, pass the file name.

Note: As a best practice, you should always add the Video object to the stage, then attach the NetStream to it, then call the NetStream object's play() method.

Enable Data Generation Mode

Call play(null) to enable "Data Generation Mode". In this mode, call the appendBytes() method to deliver data to the NetStream. Use Data Generation Mode to stream content over HTTP from the Adobe HTTP Dynamic Streaming Origin Module on an Apache HTTP Server. HTTP Dynamic Streaming lets clients seek quickly to any point in a file. The Open Source Media Framework (OSMF) supports HTTP Dynamic Streaming for vod and live streams. For examples of how to use NetStream Data Generation Mode, download the OSMF source. For more information about HTTP Dynamic Streaming, see HTTP Dynamic Streaming.

When you use this method without Flash Media Server, there are security considerations. A 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 running in Flash Player from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content. For more information related to security, see the Flash Player Developer Center Topic: Security.

Parameters
... arguments

Play a local file

The location of a media file. Argument can be a String, a URLRequest.url property, or a variable referencing either. In Flash Player and in AIR content outside the application security sandbox, 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.

Play a file from Flash Media Server

Name Required Description
name:Object Required The name of a recorded file, an identifier for live data published by NetStream.publish(), or false. If false, the stream stops playing and any additional parameters are ignored. For more information on the filename syntax, see the file format table following this table.
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. You cannot use -2 with MP3 files. 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.

You can play back the file formats described in the following table. The syntax differs depending on the file format.

File format Syntax Example
FLV Specify the stream name (in the "samples" directory) as a string without a filename extension. ns.play("samples/myflvstream");
mp3 or ID3 Specify the stream name (in the "samples" directory) as a string with the prefix mp3: or id3: without a filename extension.

ns.play("mp3:samples/mymp3stream");

ns.play("id3:samples/myid3data");

MPEG-4-based files (such as F4V and MP4) Specify the stream name (in the "samples" directory) as a string with the prefix mp4: The prefix indicates to the server that the file contains H.264-encoded video and AAC-encoded audio within the MPEG-4 Part 14 container format. If the file on the server has a file extension, specify it.

ns.play("mp4:samples/myvideo.f4v");

ns.play("mp4:samples/myvideo.mp4");

ns.play("mp4:samples/myvideo");

ns.play("mp4:samples/myvideo.mov");

RAW Specify the stream name (in the "samples" directory) as a string with the prefix raw: ns.play("raw:samples/myvideo");

Enable Data Generation Mode

To enable "Data Generation Mode", pass the value null to a NetStream created on a NetConnection connected to null. In this mode, call appendBytes() to deliver data to the NetStream. (Passing null also resets the byte counter for the onSeekPoint() callback.)

Special considerations for H.264 video in AIR 3.0 for iOS

For H.264 video, the iOS APIs for video playback accept only a URL to a file or stream. You cannot pass in a buffer of H264 video data to be decoded. Depending on your video source, pass the appropriate argument to NetStream.play() as follows:

  • For progressive playback: Pass the URL of the file (local or remote).

  • For streaming video: Pass the URL of a playlist in Apple's HTTP Live Streaming (HLS) format. This file can be hosted by any server; Flash Media Server 4.5 and higher has the advantage of being able to encode streams in HLS format.


Events
status:StatusEvent — Dispatched when attempting to play content encrypted with digital rights management (DRM). The value of the code property is "DRM.encryptedFLV".

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


Example

The following example shows how to load an external FLV file:
var MyVideo:Video = new Video();
addChild(MyVideo);
 
var MyNC:NetConnection = new NetConnection();
MyNC.connect(null);
 
var MyNS:NetStream = new NetStream(MyNC);
MyVideo.attachNetStream(MyNS);
MyNS.play("http://www.helpexamples.com/flash/video/clouds.flv");

//the clouds.flv video has metadata we're not using, so create
//an error handler to ignore the message generated by the runtime
//about the metadata
MyNS.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); 

function asyncErrorHandler(event:AsyncErrorEvent):void 
{ 
   //ignore metadata error message
}

play2()method 
public function play2(param:NetStreamPlayOptions):void

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected.

This method is an enhanced version of NetStream.play(). Like the play() method, the play2() method begins playback of a media file or queues up media files to create a playlist. When used with Flash Media Server, it can also request that the server switch to a different media file. The transition occurs seamlessly in the client application. The following features use play2() stream switching:

Dynamic streaming

Dynamic streaming (supported in Flash Media Server 3.5 and later) lets you serve a stream encoded at multiple bit rates. As a viewer's network conditions change, they receive the bitrate that provides the best viewing experience. Use the NetStreamInfo class to monitor network conditions and switch streams based on the data. You can also switch streams for clients with different capabilities. For more information, see "Dynamic streaming" in the "Adobe Flash Media Server Developer Guide".

Adobe built a custom ActionScript class called DynamicStream that extends the NetStream class. You can use the DynamicStream class to implement dynamic streaming in an application instead of writing your own code to detect network conditions. Even if you choose to write your own dynamic streaming code, use the DynamicStream class as a reference implementation. Download the class and the class documentation at the Flash Media Server tools and downloads page.

Stream reconnecting

Stream reconnecting (supported in Flash Media Server 3.5.3 and later) lets users to experience media uninterrupted even when they lose their connection. The media uses the buffer to play while your ActionScript logic reconnects to Flash Media Server. After reconnection, call NetStream.attach() to use the same NetStream object with the new NetConnection. Use the NetStream.attach(), NetStreamPlayTransitions.RESUME, and NetStreamPlayTrasitions.APPEND_AND_WAIT APIs to reconnect a stream. For more information, see the Flash Media Server 3.5.3 documentation.

Parameters
param:NetStreamPlayOptions

See also

preloadEmbeddedData()method 
public function preloadEmbeddedData(param:NetStreamPlayOptions):void

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Extracts any DRM metadata from a locally stored media file.

Use preloadEmbeddedMetaData() as the first step in downloading and caching the DRM vouchers needed for offline playback. When embedded DRM metadata is detected in a media file, a DRMContentData object is passed to the NetStream client onDRMContentData function. This DRMContentData object contains the information needed to obtain the voucher required to play the content. Pass the DRMContentDataObject to the DRMManager loadVoucher() method to download the voucher.

The steps for preloading a DRM voucher include:

Note: To use the same NetStream object to both preload metadata and play content, wait for the onPlayStatus call generated by the preload operation before starting playback.

Downloaded vouchers are stored in a local cache. Playing content online also downloads and caches vouchers. When a DRM-protected content file is viewed, a cached voucher is retrieved from the local store automatically. Use the DRMManager to manage the voucher cache.

Notes: Preloading DRM metadata through HTTP, HTTPS, or RTMP connections is not supported. You can only preload metadata from files stored on the file system.

Parameters
param:NetStreamPlayOptions — A NetStreamPlayOptions describing the options to use while processing the content file.

See also

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

Language version: ActionScript 3.0
Runtime version: 

Sends streaming audio, video, and data messages from a client to Flash Media Server, optionally recording the stream during transmission. This method dispatches a NetStatusEvent object with information about the stream. Before you call NetStream.publish(), capture the "NetConnection.Connect.Success" event to verify that the application has successfully connected to Flash Media Server.

While publishing, you can record files in FLV or F4V format. If you record a file in F4V format, use a flattener tool to edit or play the file in another application. To download the tool, see www.adobe.com/go/fms_tools.

Note:Do not use this method to play a stream. To play a stream, call the NetStream.play() method.

Workflow for publishing a stream

  1. Create a NetConnection object and call NetConnection.connect().
  2. Call NetConnection.addEventListener() to listen for NetStatusEvent events.
  3. On the "NetConnection.Connect.Success" event, create a NetStream object and pass the NetConnection object to the constructor.
  4. To capture audio and video, call the NetStream.attachAudio()method and the NetStream.attachCamera() method.
  5. To publish a stream, call the NetStream.publish() method. You can record the data as you publish it so that users can play it back later.

Note: A NetStream can either publish a stream or play a stream, it cannot do both. To publish a stream and view the playback from the server, create two NetStream objects. You can send multiple NetStream objects over one NetConnection object.

When Flash Media Server records a stream it creates a file. By default, the server creates a directory with the application instance name passed to NetConnection.connect() and stores the file in the directory. For example, the following code connects to the default instance of the "lectureseries" application and records a stream called "lecture". The file "lecture.flv" is recorded in the applications/lectureseries/streams/_definst_ directory:

     var nc:NetConnection = new NetConnection();
     nc.connect("rtmp://fms.example.com/lectureseries");
     nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
     
     function netStatusHandler(event:NetStatusEvent):void
     {
       if (event.info.code == "NetConnection.Connect.Success")
       {
            var ns:NetStream = new NetStream(nc);
            ns.publish("lecture", "record");
       }
     }
     

The following example connects to the "monday" instance of the same application. The file "lecture.flv" is recorded in the directory /applications/lectureseries/streams/monday:

     var nc:NetConnection = new NetConnection();
     nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
     nc.connect("rtmp://fms.example.com/lectureseries/monday");
     
     function netStatusHandler(event:NetStatusEvent):void
     {
       if (event.info.code == "NetConnection.Connect.Success")
       {
            var ns:NetStream = new NetStream(nc);
            ns.publish("lecture", "record");
       }
     }
     
Parameters
name:String (default = null) — A string that identifies the stream. Clients that subscribe to this stream pass this name when they call NetStream.play(). Don't follow the stream name with a "/". For example, don't use the stream name "bolero/".

You can record files in the formats described in the following table (you cannot use publish() for MP3 format files). The syntax differs depending on the file format.

File format Syntax Example
FLV Specify the stream name as a string without a filename extension. ns.publish("myflvstream");
MPEG-4-based files (such as F4V or MP4) Specify the stream name as a string with the prefix mp4: with or without the filename extension. Flash Player encodes using H.263, not H.264. Flash Media Server can record any codec in the F4V container. Flash Media Live Encoder can encode using H.264. ns.publish("mp4:myvideo.f4v")
ns.publish("mp4:myvideo");
RAW Specify the stream name as a string with the prefix raw: ns.publish("raw:myvideo");

 
type:String (default = null) — A string that specifies how to publish the stream. Valid values are "record", "append", "appendWithGap", and "live". The default value is "live".
  • If you pass "record", the server publishes and records live data, saving the recorded data to a new file with a name matching the value passed to the name parameter. If the file exists, it is overwritten.
  • If you pass "append", the server publishes and records live data, appending the recorded data to a file with a name that matches the value passed to the name parameter. If no file matching the name parameter is found, it is created.
  • If you pass "appendWithGap", additional information about time coordination is passed to help the server determine the correct transition point when dynamic streaming.
  • If you omit this parameter or pass "live", the server 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


Example
The following example captures video from a camera and publishes it over a NetStream to Flash Media Server. The example displays the video as it's played back from Flash Media Server.

To run this example, you need a camera attached to your computer. You also need to add a Button component and a Label component to the Library.

The application has a button that publishes a stream (sends it to Flash Media Server) only after the application has successfully connected to the server. The application plays back the stream from the server only after the stream has been successfully published. The NetStatusEvent returns an info object with a code property that specifies these cases. The netStatusHandler function handles these events for the NetConnection and NetStream classes.


package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Video;
    import flash.media.Camera;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import fl.controls.Button;
    import fl.controls.Label;

    public class NetStream_publish extends Sprite {
        private var connectionURL:String = "rtmp://localhost/live/";
        private var videoURL:String = "liveVideo";
        private var nc:NetConnection;
        private var ns_publish:NetStream;
        private var ns_playback:NetStream;
        private var video_publish:Video;
        private var video_playback:Video;
        private var cam:Camera;
		private var b:Button;
		private var l:Label;

        public function NetStream_publish() {
			setUpUI();
			
            nc = new NetConnection();
            nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			
			// Add bandwidth detection handlers on the NetConnection Client to
			// prevent Reference Errors at runtime when using the "live" and "vod" applications.		  
			var clientObj:Object = new Object();
			clientObj.onBWDone = onBWDone;
			clientObj.onBWCheck = onBWCheck;
			nc.client = clientObj;
			
			// Connect to the "live" application on Flash Media Server.
            nc.connect(connectionURL);
        }

        private function netStatusHandler(event:NetStatusEvent):void {
			trace(event.info.code + " | " + event.info.description);
            switch (event.info.code) {
                case "NetConnection.Connect.Success":
					// Enable the "Publish" button after the client connects to the server.
					b.enabled = true;
					break;
                case "NetStream.Publish.Start":
					playbackVideo();
					break;
            }
        }
	
        private function publishVideo(event:MouseEvent):void{
			// Disable the button so that you can only publish once.
			b.enabled = false;
            // Create a NetStream to send video to FMS.
            ns_publish = new NetStream(nc);
            ns_publish.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            // Publish (send) the video to FMS.
            cam = Camera.getCamera();
            ns_publish.attachCamera(cam);
           	ns_publish.publish(videoURL);
        }

        private function playbackVideo():void {
            // Create the Video object to show the video on the stage
            video_playback = new Video(cam.width, cam.height);
            video_playback.x = cam.width + 20;
            video_playback.y = 10;
            addChild(video_playback);
            // Create a NetStream to receive the video from FMS.
            ns_playback = new NetStream(nc);
            ns_playback.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            // Display the video that was published to FMS.
			      video_playback.attachNetStream(ns_playback);
            ns_playback.play(videoURL); 
        }
		
		
		private function setUpUI():void { 
      b = new Button(); 
      b.addEventListener(MouseEvent.CLICK, publishVideo);
      b.width = 150;
			b.label = "Publish video to server";
			b.move(10, 150);
			b.enabled = false;
			
			l = new Label();
			l.width = 150;
			l.text = "Playing back from server"
			l.move(190, 150);
			
			addChild(b);
			addChild(l);
		}
		
		// Handlers called by the Flash Media Server "live" and "vod" applications.
		public function onBWDone(... rest):Boolean {
			return true;
		}
		
		public function onBWCheck(... rest):Number {
			return 0;
		}
    }
}

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

Language version: ActionScript 3.0
Runtime version: 

Specifies whether incoming audio plays on the stream. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, attach this method to a button to allow users to mute and unmute the audio. Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method.

Parameters
flag:Boolean — Specifies whether incoming audio plays on the stream (true) or not (false). The default value is true. If the specified stream contains only audio data, NetStream.time stops incrementing when you pass false.
receiveVideo()method 
public function receiveVideo(flag:Boolean):void

Language version: ActionScript 3.0
Runtime version: 

Specifies whether incoming video plays on the stream. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, attach this method to a button to allow users to show and hide the video. Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method.

Parameters
flag:Boolean — Specifies whether incoming video plays on this stream (true) or not (false). The default value is true. If the specified stream contains only video data, NetStream.time stops incrementing when you pass false.
receiveVideoFPS()method 
public function receiveVideoFPS(FPS:Number):void

Language version: ActionScript 3.0
Runtime version: 

Specifies the frame rate for incoming video. This method is available only to clients subscribed to the specified stream. It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. For example, call this method to allow users to set the video frame rate. To determine the current frame rate, use NetStream.currentFPS. To stop receiving video, pass 0.

When 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. Between every two keyframes, the server sends the minimum number of frames needed to satisfy the desired rate. Please note that I-frames (or intermediate frames) must be sent contiguously, otherwise the video is 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.

Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the NetStream.appendBytes() method.

Parameters
FPS:Number — Specifies the frame rate per second at which the incoming video plays.
resume()method 
public function resume():void

Language version: ActionScript 3.0
Runtime version: 

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

See also

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

Language version: ActionScript 3.0
Runtime version: 

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-50 frames.

Flash Media Server has several types of seek behavior: enhanced seeking and smart seeking.

Enhanced seeking

Enhanced seeking is enabled by default. To disable enhanced seeking, on Flash Media Server set the EnhancedSeek element in the Application.xml configuration file to false.

If enhanced seeking is enabled, the server generates a new keyframe at offset based on the previous keyframe and any intervening P-frames. However, generating keyframes 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.

If enhanced seeking is disabled, the server starts streaming from the nearest keyframe. For example, suppose a video has keyframes at 0 seconds 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.

Smart seeking

To enable smart seeking, set NetStream.inBufferSeek to true.

Smart seeking allows Flash Player to seek within an existing back buffer and forward buffer. When smart seeking is disabled, each time seek() is called Flash Player flushes the buffer and requests data from the server. For more information, see NetStream.inBufferSeek.

Seeking in Data Generation Mode

When you call seek() on a NetStream in Data Generation Mode, all bytes passed to appendBytes() are discarded (not placed in the buffer, accumulated in the partial message FIFO, or parsed for seek points) until you call appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) or appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK) to reset the parser. For information about Data Generation Mode, see NetStream.play().

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

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

Language version: ActionScript 3.0
Runtime version: 

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

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

You can call the send() method to add data keyframes to a live stream published 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);
     
     var ns = new air.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.

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 send; 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 causes 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 Developer Guide 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


Example
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.client = new CustomClient();
               vid.attachNetStream(ns2);
               ns2.play("dummy");
               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);
    }
 }

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("&#64;setDataFrame", "onMetaData", metaData);
            ns.attachCamera( Camera.getCamera() );
            ns.attachAudio( Microphone.getMicrophone() );    	
	}
}

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

 // 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);

 //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);

step()method 
public function step(frames:int):void

Language version: ActionScript 3.0
Runtime version: AIR 2

Steps forward or back the specified number of frames, relative to the currently displayed frame. Specify a positive number to step forward and a negative number to step in reverse. Call this method to create accurate fast forward or rewind functionality.

Note: This method is not supported for H.264 video in AIR 3.0 for iOS.

This method is available only when data is streaming from Flash Media Server 3.5.3 or higher and when NetStream.inBufferSeek is true. Also, the target frame must be in the buffer. For example, if the currently displayed frame is frame number 120 and you specify a value of 1000, the method fails if frame number 1120 is not in the buffer.

This method is intended to be used with the pause() or togglePause() methods. If you step 10 frames forward or backward during playback without pausing, you may not notice the steps or they'll look like a glitch. Also, when you call pause() or togglePause the audio is suppressed.

If the call to NetStream.step() is successful, a NetStatusEvent is sent with "NetStream.Step.Notify" as the value of the info object's code property.

Parameters
frames:int

See also

togglePause()method 
public function togglePause():void

Language version: ActionScript 3.0
Runtime version: 

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

Event detail
asyncErrorevent 
Event object type: flash.events.AsyncErrorEvent
AsyncErrorEvent.type property = flash.events.AsyncErrorEvent.ASYNC_ERROR

Language version: ActionScript 3.0
Runtime version: 

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:

PropertyValue
bubblesfalse This property applies to ActionScript 3.0 display objects (in SWF files).
cancelablefalse; there is no default behavior to cancel. This property applies to display objects in SWF content, which use the ActionScript 3.0 display architecture.
currentTargetThe object that is actively processing the Event object with an event listener. This property applies to display objects in SWF content, which use the ActionScript 3.0 display architecture.
target The object dispatching the event.
errorThe error that triggered the event.

See also

drmAuthenticateevent  
Event object type: flash.events.DRMAuthenticateEvent
DRMAuthenticateEvent.type property = flash.events.DRMAuthenticateEvent.DRM_AUTHENTICATE

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted content that requires a user credential for authentication before playing.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

Use the setDRMAuthenticationCredentials() method of the NetStream object to authenticate the user. If user authentication failed, the application retries authentication and dispatches a new DRMAuthenticateEvent event for the NetStream object.

The DRMAuthenticateEvent.AUTHENTICATION_TYPE_PROXY constant defines the value of the authenticationType property of a DRMAuthenticateEvent object.

This event has the following properties:

PropertyValue
authenticationTypeIndicates whether the supplied credentials are for authenticating against the Flash Media Rights Management Server (FMRMS) or a proxy server.
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
headerThe encrypted content file header provided by the server.
netstreamThe NetStream object that initiated this event.
passwordPromptA prompt for a password credential, provided by the server.
targetThe NetStream object.
urlPromptA prompt for a URL to display, provided by the server.
usernamePromptA prompt for a user name credential, provided by the server.

See also

drmErrorevent  
Event object type: flash.events.DRMErrorEvent
DRMErrorEvent.type property = flash.events.DRMErrorEvent.DRM_ERROR

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted file, encounters a DRM-related error. For example, a DRMErrorEvent object is dispatched when the user authorization fails. This may be because the user has not purchased the rights to view the content or because the content provider does not support the viewing application.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

The DRMErrorEvent.DRM_ERROR constant defines the value of the type property of a drmError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
errorIDA numerical error code assigned to the problem.
subErrorIDAn error code that indicates more detailed information about the underlying problem.
targetThe NetStream object.

See also

drmStatusevent  
Event object type: flash.events.DRMStatusEvent
DRMStatusEvent.type property = flash.events.DRMStatusEvent.DRM_STATUS

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Dispatched when the digital rights management (DRM) encrypted content begins playing (when the user is authenticated and authorized to play the content).

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

DRMStatusEvent object contains information related to the voucher, such as whether the content is available offline or when the voucher expires and users can no longer view the content.

The DRMStatusEvent.DRM_STATUS constant defines the value of the type property of a drmStatus event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
detailA string explaining the context of the status event.
isAnonymousIndicates whether the content protected with DRM encryption is available without requiring a user to provide authentication credentials.
isAvailableOfflineIndicates whether the content protected with DRM encryption is available offline.
offlineLeasePeriodThe remaining number of days that content can be viewed offline.
policiesA custom object of the DRM status event.
targetThe NetStream object.
voucherEndDateThe absolute date on which the voucher expires and the content can no longer be viewed by users
contentDataThe DRMContentData for the content
voucherThe DRMVoucher object for the content.
isLocalIndicates whether the content is stored on the local file system

See also

ioErrorevent  
Event object type: flash.events.IOErrorEvent
IOErrorEvent.type property = flash.events.IOErrorEvent.IO_ERROR

Language version: ActionScript 3.0
Runtime version: 

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:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
errorIDA reference number associated with the specific error (AIR only).
targetThe network object experiencing the input/output error.
textText to be displayed as an error message.
mediaTypeDataevent  
Event object type: flash.events.NetDataEvent

Language version: ActionScript 3.0
Runtime version: AIR 2.7

Dispatched when playing video content and certain type of messages are processed.

A NetDataEvent is dispatched for the following messages:

Note: This event is not dispatched by content running in Flash Player in the browser on Android or Blackberry Tablet OS or by content running in AIR on iOS.

netStatusevent  
Event object type: flash.events.NetStatusEvent
NetStatusEvent.type property = flash.events.NetStatusEvent.NET_STATUS

Language version: ActionScript 3.0
Runtime version: 

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:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
infoAn object with properties that describe the object's status or error condition.
targetThe NetConnection or NetStream object reporting its status.

See also

onCuePointevent  

Language version: ActionScript 3.0
Runtime version: 

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 www.adobe.com/go/learn_fms_fileformats_en.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

onCuePoint is actually a property of the NetStream.client object. IThe property 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 onCuePoint as an event. Define a callback function and attach it to one of the following objects:

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

You can embed the following types of cue points in a video file:

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 An associative array of name and 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.


Example
The following example shows how you can load external FLV files and respond to metadata and cue points. Example provided by ActionScriptExamples.com.
var video:Video = new Video();
addChild(video);
 
var nc:NetConnection = new NetConnection();
nc.connect(null);
 
var ns:NetStream = new NetStream(nc);
ns.client = {};
ns.client.onMetaData = ns_onMetaData;
ns.client.onCuePoint = ns_onCuePoint;

video.attachNetStream(ns);
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");

 
function ns_onMetaData(item:Object):void {
    trace("metaData");
    // Resize video instance.
    video.width = item.width;
    video.height = item.height;
    // Center video instance on Stage.
    video.x = (stage.stageWidth - video.width) / 2;
    video.y = (stage.stageHeight - video.height) / 2;
}
 
function ns_onCuePoint(item:Object):void {
    trace("cuePoint");
    trace(item.name + "\t" + item.time);
}

See also

onDRMContentDataevent  

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

A DRMContentData object contains the information needed to obtain a voucher required to play a DRM-protected media file. Use the DRMManager class to download the voucher with this information.

onDRMContentData is a property of the NetStream.client object. This property is listed in the Events section because it responds to a data event when preloading embedded data from a local media file. For more information, see the NetStream class description. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for, or process onDRMContentData as an event. Rather, you must define a single callback function and attach it directly to one of the following objects:

See also

onImageDataevent  

Language version: ActionScript 3.0
Runtime version: 

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.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

onImageData is actually a property of the NetStream.client object. The property 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. Define a single callback function and attach it to one of the following objects:

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 my_video:Video = new Video();
                addChild(my_video);

                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.client = customClient;

                my_video.attachNetStream(my_ns);
                my_ns.play("yourURL");
            }

            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

onMetaDataevent  

Language version: ActionScript 3.0
Runtime version: 

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 www.adobe.com/go/learn_fms_fileformats_en.

onMetaData is actually a property of the NetStream.client object. The property 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. Define a single callback function and attach it to one of the following objects:

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.


Example
The following example shows how you can load external FLV files and respond to metadata and cue points. Example provided by ActionScriptExamples.com.
var video:Video = new Video();
addChild(video);
 
var nc:NetConnection = new NetConnection();
nc.connect(null);
 
var ns:NetStream = new NetStream(nc);
ns.client = {};
ns.client.onMetaData = ns_onMetaData;
ns.client.onCuePoint = ns_onCuePoint;

video.attachNetStream(ns);
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");

 
function ns_onMetaData(item:Object):void {
    trace("metaData");
    // Resize video instance.
    video.width = item.width;
    video.height = item.height;
    // Center video instance on Stage.
    video.x = (stage.stageWidth - video.width) / 2;
    video.y = (stage.stageHeight - video.height) / 2;
}
 
function ns_onCuePoint(item:Object):void {
    trace("cuePoint");
    trace(item.name + "\t" + item.time);
}

See also

onPlayStatusevent  

Language version: ActionScript 3.0
Runtime version: 

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. The property 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 onPlayStatus as an event. Define a callback function and attach it to one of the following objects:

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.
NetStream.Play.TransitionComplete "status" The subscriber is switching to a new stream as a result of stream bit-rate switching

See also

onSeekPointevent  

Language version: ActionScript 3.0
Runtime version: AIR 2

Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable point (for example, a video key frame). Use this event to construct a seek point table. The byteCount corresponds to the byteCount at the first byte of the parseable message for that seek point, and is reset to zero as described above. To seek, at the event NetStream.Seek.Notify, find the bytes that start at a seekable point and call appendBytes(bytes). If the bytes argument is a ByteArray consisting of bytes starting at the seekable point, the video plays at that seek point.

Note: Calls to appendBytes() from within this callback are ignored.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

The onSeekPoint property is a property of the NetStream.client object. The property is listed in the Events section because it responds to data coming into the appendBytes() method. 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 onSeekPoint as an event. To use onSeekPoint, define a callback function and attach it to one of the following objects:

See also

onTextDataevent  

Language version: ActionScript 3.0
Runtime version: 

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.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

onTextData is actually a property of the NetStream.client object. The property 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 onTextData as an event. Define a callback function and attach it to one of the following objects:

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 my_video:Video = new Video();
                addChild(my_video);

                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.client = customClient;

                my_video.attachNetStream(my_ns);
                my_ns.play("yourURL");
            }

            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

onXMPDataevent  

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Establishes a listener to respond when Flash Player receives information specific to Adobe Extensible Metadata Platform (XMP) embedded in the video being played. For information about video file formats supported by Flash Media Server, see the www.adobe.com/go/learn_fms_fileformats_en.

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

onXMPData is actually a property of the NetStream.client object. The property 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. Define a callback function and attach it to one of the following objects:

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

The object passed to the onXMPData() event handling function has one data property, which is a string. The string is generated from a top-level UUID box. (The 128-bit UUID of the top level box is BE7ACFCB-97A9-42E8-9C71-999491E3AFAC.) This top-level UUID box contains exactly one XML document represented as a null-terminated UTF-8 string.

See also

statusevent  
Event object type: flash.events.StatusEvent
StatusEvent.type property = flash.events.StatusEvent.STATUS

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Dispatched when the application attempts to play content encrypted with digital rights management (DRM), by invoking the NetStream.play() method. The value of the status code property will be "DRM.encryptedFLV".

Note: This event is not supported for H.264 video in AIR 3.0 for iOS.

Defines the value of the type property of a status event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
codeA description of the object's status.
currentTargetThe object that is actively processing the Event object with an event listener.
levelThe category of the message, such as "status", "warning" or "error".
targetThe object reporting its status.

See also

Constant detail
CONNECT_TO_FMSconstant
public static const CONNECT_TO_FMS:String = "connectToFMS"

Language version: ActionScript 3.0
Runtime version: AIR 1.5

A static object used as a parameter to the constructor for a NetStream instance. It is the default value of the second parameter in the NetStream constructor; it is not used by the application for progressive media playback. When used, this parameter causes the constructor to make a connection to a Flash Media Server instance.

DIRECT_CONNECTIONSconstant 
public static const DIRECT_CONNECTIONS:String = "directConnections"

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Creates a peer-to-peer publisher connection. Pass this string for the second (optional) parameter to the constructor for a NetStream instance. With this string, an application can create a NetStream connection for the purposes of publishing audio and video to clients.

Examples
examples\NetConnectionExample
The following example uses a Video object with the NetConnection and NetStream classes to load and play an FLV 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 = "http://www.helpexamples.com/flash/video/cuepoints.flv";
        private var connection:NetConnection;
        private var stream:NetStream;
        private var video:Video = new Video();    	

        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 {
            addChild(video);
            var stream:NetStream = new NetStream(connection);
            stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            stream.client = new CustomClient();
            video.attachNetStream(stream);
            stream.play(videoURL);
        }
    }
}

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);
    }
}
examples\NetConnectionExample.2
You can get metadata using a function, instead of creating a custom class. The following suggestion, provided by Bill Sanders, shows how to edit the NetConnectionExample code above to call metadata within a function. In this case, the object mdata is used to set up the width and height of a video instance video:
  //Place the following in the connectStream() function
  //in the NetConnectionExample code
  var metaSniffer:Object=new Object();  
  stream.client=metaSniffer; //stream is the NetStream instance  
  metaSniffer.onMetaData=getMeta;  
      
   
  // Add the following function within the NetConnectionExample class  
  private function getMeta (mdata:Object):void  
  {  
     video.width=mdata.width/2;  
     video.height=mdata.height/2;  
  }