View comments | RSS feed
Packageflash.net
Classpublic class NetStream
InheritanceNetStream Inheritance EventDispatcher Inheritance Object

The NetStream class opens a one-way streaming connection between Flash Player and a server, such as Adobe's Macromedia Flash Media Server 2 or Adobe Flex, or between Flash Player and the local file system through a connection made available by a NetConnection object. A NetStream object is like a channel inside a NetConnection object; this channel can either publish audio and/or video data, using NetStream.publish(), or subscribe to a published stream and receive data, using NetStream.play(). You can publish or play live (real-time) data and previously recorded data. You can also use NetStream objects to send text messages to all subscribed clients (see the NetStream.send() method).

Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance and memory management, and independent video and Flash frame rates. This class provides several methods and properties you can use to track the progress of the file as it loads and plays, and to give the user control over playback (stopping, pausing, and so on).

Some of the properties and methods in the NetStream class are intended for use primarily with a server, such as Flash Media Server or Flex. They may contain additional server-side functionality. For additional documentation, see the NetStream class in Flash Media Server documentation.

For more information on video playback, see "Playing back external FLV files dynamically" in Learning ActionScript 2.0 in Flash.

General workflow for streaming audio or video. The following steps summarize the general sequence of actions required for publishing real-time audio and video:

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

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

View the examples.

See also

flash.media.Video
flash.net.NetConnection
send()


Public Properties
 PropertyDefined by
  bufferLength : Number
[read-only] The number of seconds of data currently in the buffer.
NetStream
  bufferTime : Number
Specifies how long to buffer messages before starting to display the stream.
NetStream
  bytesLoaded : uint
[read-only] The number of bytes of data that have been loaded into the player.
NetStream
  bytesTotal : uint
[read-only] The total size in bytes of the file being loaded into the player.
NetStream
  checkPolicyFile : Boolean
Specifies whether Flash Player should try to download a cross-domain policy file from the loaded FLV file's server before beginning to load the FLV file.
NetStream
  client : Object
Specifies the object on which callback methods are invoked.
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
  liveDelay : Number
[read-only] The number of seconds of data in the subscribing stream's buffer in live (unbuffered) mode.
NetStream
  objectEncoding : uint
[read-only] The object encoding (AMF version) for this NetStream object.
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
Public Methods
 MethodDefined by
  
Creates a stream that can be used for playing FLV files through the specified 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
  
Specifies an audio stream sent over the NetStream object, from a Microphone object passed as the source.
NetStream
  
attachCamera(theCamera:Camera, snapshotMilliseconds:int = -1):void
Starts capturing video from the specified source, 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
 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
  
Pauses playback of a video stream.
NetStream
  
play(... arguments):void
Begins playback of external audio or a video (FLV) 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 text messages from a client to a server, such as Flash Media Server 2, optionally recording the stream during transmission.
NetStream
  
Specifies whether incoming audio plays on the stream.
NetStream
  
Specifies whether incoming video will play on the stream.
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 closest to the specified location (an offset, in seconds, from the beginning of the stream).
NetStream
  
send(handlerName:String, ... arguments):void
Sends a message on the specified stream to all subscribing clients.
NetStream
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
Pauses or resumes playback of a stream.
NetStream
 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
   Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.NetStream
   Dispatched when an input or output error occurs that causes a network operation to fail.NetStream
   Dispatched when a NetStream object is reporting its status or error condition.NetStream
   Invoked when an embedded cue point is reached while playing an FLV file.NetStream
   Dispatched when Flash Player receives descriptive information embedded in the FLV file being played.NetStream
   Dispatched when a NetStream object has completely played a stream.NetStream
Property detail
bufferLengthproperty
bufferLength:Number  [read-only]

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

Implementation
    public function get bufferLength():Number

See also

bufferTimeproperty 
bufferTime:Number  [read-write]

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

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

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

See also

bytesLoadedproperty 
bytesLoaded:uint  [read-only]

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

Implementation
    public function get bytesLoaded():uint

See also

bytesTotalproperty 
bytesTotal:uint  [read-only]

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

Implementation
    public function get bytesTotal():uint

See also

checkPolicyFileproperty 
checkPolicyFile:Boolean  [read-write]

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

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

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

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

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

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

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

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

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

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

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

See also

clientproperty 
client:Object  [read-write]

Specifies the object on which callback methods are invoked. The default object is this, the NetStream object being created. If you set the client property to another object, callback methods will be invoked on that other object.

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.
currentFPSproperty 
currentFPS:Number  [read-only]

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

Implementation
    public function get currentFPS():Number
liveDelayproperty 
liveDelay:Number  [read-only]

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

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

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

Implementation
    public function get liveDelay():Number
objectEncodingproperty 
objectEncoding:uint  [read-only]

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

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

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

Implementation
    public function get objectEncoding():uint

See also

soundTransformproperty 
soundTransform:SoundTransform  [read-write]

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

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

See also

timeproperty 
time:Number  [read-only]

The position of the playhead, in seconds.

Implementation
    public function get time():Number

See also

Constructor detail
NetStream()constructor
public function NetStream(connection:NetConnection)

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

Parameters
connection:NetConnection — A NetConnection object.

Throws
ArgumentError — The NetConnection instance is not connected.

See also

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

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

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

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

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

See also

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

Starts capturing video from the specified source, 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 primarily for use with a server, such as Flash Media Server; for more information, see the class description.

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

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

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

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

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

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

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

See also

pause()method 
public function pause():void

Pauses playback of a video stream. Calling this method does nothing if the video is already paused.

See also

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

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

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

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

When you use this method, consider the Flash Player security model.

For more information, see the following:

Parameters
... arguments — The location of the FLV file to play, as a URLRequest object or a string. You can play local FLV 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.

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.

See also

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

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

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

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

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

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

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

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

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

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

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

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

See also

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

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

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

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

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

Parameters
flag:Boolean — Specifies whether incoming audio plays on the specified stream (true) or not (false). The default value is true.
receiveVideo()method 
public function receiveVideo(flag:Boolean):void

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

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

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

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

Parameters
flag:Boolean — Specifies whether incoming video plays on the specified stream (true) or not (false). The default value is true.
resume()method 
public function resume():void

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

Seeks the keyframe closest to the specified location (an offset, in seconds, from the beginning of the stream). The stream resumes playing when that location is reached.

Parameters
offset:Number — The approximate time value, in seconds, to move to in an FLV file. The playhead moves to the video keyframe that's closest to 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, 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).

The precise location to which a video seeks depends on the frames per second (fps) setting at which it was exported. Therefore, if you export the same video at 6 fps and 30 fps, and you use myStream.seek(15) for both video objects, the videos seek to two different locations.

See also

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

Sends a message on the specified stream to all subscribing clients. This method is available only to the publisher of the specified stream.

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

To process and respond to the message, create a handler in the format myStream.HandlerName.

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

Parameters
handlerName:String — The message to be sent; also the name of the ActionScript handler to receive the message. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the stream object. Do not use a reserved term for a handler name. For example, using "close" as a handler name will cause the method to fail.
 
... 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.

See also


Example
The following example sets up two NetStream objects in the same file. One NetStream object, ns1. is used to call the send() method, and the other, ns2, registers a client object that registers a handler function for the send() call:
  import flash.net.NetConnection;
  import flash.net.NetStream;
  import flash.events.NetStatusEvent;
  import flash.media.Video;
  import flash.utils.setTimeout;
  
  var nc:NetConnection = new NetConnection();
  nc.objectEncoding = 0;
  nc.addEventListener("netStatus", onNCStatus);
  nc.connect("rtmp://www.example.com/MyApp/MyInstance");
  var ns1:NetStream;
  var vid:Video = new Video(300,300);
  addChild(vid);
  var obj:Object = new Object();
  obj.myFunction = function(event:String):void {
   trace(event);
  }
  
  function onNCStatus(event:NetStatusEvent):void {
   if(event.info.code == "NetConnection.Connect.Success") {
    ns1 = new NetStream(nc);
    ns1.play("MyVideo");
    vid.attachNetStream(ns1);
    ns1.client = obj;
    ns1.publish("dummy", "live");
    
    var ns2:NetStream = new NetStream(nc);
    ns2.play("dummy");
    ns2.client = obj;
    
    setTimeout(sendHello, 3000);
   }
  }
  
  function sendHello():void {
    ns1.send("myFunction", "hello");
  }
  

togglePause()method 
public function togglePause():void

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

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
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object experiencing a network operation failure.
errorThe error that triggered the event.

See also

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

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.
targetThe network object experiencing the input/output error.
textText to be displayed as an error message.
netStatusevent  
Event object type: flash.events.NetStatusEvent
NetStatusEvent.type property = flash.events.NetStatusEvent.NET_STATUS

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  

Invoked when an embedded cue point is reached while playing an FLV file. You can use this handler 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.

This event is intended primarily for use with a server, such as Flash Media Server 2; for more information, see the class description. It is not part of the Flash Player API, but is included in this language reference for your convenience. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process this event. Rather, you must define a single callback function and attach it directly to one of the following objects:

The following types of cue points can be embedded in an FLV 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 FLV file.
parameters A associative array of name/value pair strings specified for this cue point. Any valid string can be used for the parameter name or value.
time The time in seconds at which the cue point occurred in the video file during playback.
type The type of cue point that was reached, either navigation or event.

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

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

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

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

See also

onMetaDataevent  

Dispatched when Flash Player receives descriptive information embedded in the FLV file being played.

This special event is primarily intended for use with a server, such as Flash Media Server; for more information, see the class description. It is not technically part of the Flash Player API, but is included in this language reference for your convenience. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process this event. Rather, you must define a single callback function and attach it directly 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.

This event 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 FLV 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.

See also

onPlayStatusevent  

Dispatched when a NetStream object has completely played a stream. This handler returns information objects that provide information in addition to what's returned by the netStatus event. You can use this handler 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). To respond to this event, you must create a function to process the information object sent by the server.

This event is intended primarily for use with a server, such as Flash Media Server; for more information, see the class description. It is not part of the Flash Player API, but is included in this language reference for your convenience. You cannot use the addEventListener() method, or any other EventDispatcher methods, to listen for or process this event. Rather, you must define a single callback function and attach it directly 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.

See also

Examples

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

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


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

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

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

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

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

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

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




Comments


djtechwriter said on Jun 28, 2006 at 5:51 PM :
The Netstream.play() description needs the following clarification about playing a remote FLV file:

A SWF file in the local-trusted or local-with-networking sandbox can load and play an FLV file from the remote sandbox, but cannot access that remote FLV file's data without explicit permission in the form of a cross-domain policy file. The NetStream.checkPolicyFile property description has more information on this issue.

- Dave Jacowitz, Flash Team
peterd_mm said on Jul 25, 2006 at 8:22 PM :
The bytesTotal property, returns 0 if the number of total bytes can't be determined (for example, if the download was initiated but the server did not transmit an HTTP content-length).

Peter
Flash Player documentation
Adobe Systems Incorporated

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/2/langref/flash/net/NetStream.html