PackageTop Level
Classpublic dynamic class NetStream
InheritanceNetStream Inheritance Object

Player version: Flash Player 7

The NetStream class provides methods and properties for playing Flash Video (FLV) files from the local file system or an HTTP address. You use a NetStream object to stream video through a NetConnection object. 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 a number of 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).



Public Properties
 Property
  bufferLength : Number
[read-only]The number of seconds of data currently in the buffer.
  bufferTime : Number
[read-only]The number of seconds assigned to the buffer by NetStream.setBufferTime().
  bytesLoaded : Number
[read-only]The number of bytes of data that have been loaded into the player.
  bytesTotal : Number
[read-only]The total size in bytes of the file being loaded into the player.
  checkPolicyFile : Boolean
Specifies whether Flash Player should attempt to download a policy file from the loaded FLV file's server before beginning to load the FLV file itself.
  currentFps : Number
[read-only]The number of frames per second being displayed.
  liveDelay : Number
[read-only]The number of seconds of data in the specified subscribing stream’s buffer in live (unbuffered) mode.
  maxPauseBufferTime : Number
Specifies the maximum number of seconds to buffer messages during pause mode.
  time : Number
[read-only]The position of the playhead, in seconds.
 Properties inherited from class Object
 __proto__, __resolve, constructor, prototype
Public Methods
 Method
  
Creates a stream that can be used for playing FLV files through the specified NetConnection object.
  
attachAudio(theMicrophone:Microphone):Void
Specifies an audio stream to be sent over the NetStream object.
  
attachVideo(theCamera:Camera, snapshotMilliseconds:Number):Void
Starts capturing video from the specified source, or stops capturing if the theCamera is null.
  
close():Void
Stops playing all data on the stream, sets the NetStream.time property to 0, and makes the stream available for another use.
  
Returns an object containing various Quality of Service (QOS) statistics related to a NetStream object and its underlying streaming buffer for audio, video, and data.
  
pause([flag:Boolean]):Void
Pauses or resumes playback of a stream.
  
play(name:Object, start:Number, len:Number, reset:Object):Void
Begins playback of an external video (FLV) file.
  
play2(playParam:Object):Void
Plays streaming audio, video, and text messages being published to Flash Media Server, or plays a recorded stream stored on the server.
  
publish(name:Object, type:String):Void
Sends streaming audio, video, and text messages from clients to Flash Media Server, optionally recording the stream to a file during transmission.
  
receiveAudio(receive:Boolean):Void
Specifies whether incoming audio plays on the specified stream.
  
receiveVideo(receive:Boolean):Void
Specifies whether incoming video plays on the specified stream or specifies the frame rate of the video.
  
seek(offset:Number):Void
Seeks the keyframe closest to the specified number of seconds from the beginning of the stream.
  
send(handlerName:String, [optionalArgs:]):Void
Broadcasts a message on the specified stream to all subscribing clients.
  
setBufferTime(bufferTime:Number):Void
Specifies how long to buffer messages before starting to display the stream.
 Methods inherited from class Object
 addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch
Events
 EventSummaryDefined by
  
onCuePoint = function(infoObject:Object) {}
Invoked when an embedded cue point is reached while playing an FLV file.NetStream
  
onMetaData = function(infoObject:Object) {}
Invoked when the Flash Player receives descriptive information embedded in the FLV file being played.NetStream
  
onPlayStatus = function(infoObject:Object) {}
Invoked when a NetStream object has completely played a stream.NetStream
  
onStatus = function(infoObject:Object) {}
Invoked every time a status change or error is posted for the NetStream object.NetStream
  
onTextData = function(textData:Object) {}
Invoked when a NetStream object receives text data embedded in a media file that is playing.NetStream
  
onXMPData = function(data:Object) {}
Invoked when a NetStream object receives receives information specific to Adobe Extensible Metadata Platform (XMP) metadata embedded in the media being played.NetStream
Property detail
bufferLengthproperty
bufferLength:Number  [read-only]

Player version: Flash Player 7 — Note: This property is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

The number of seconds of data currently in the buffer. You can use this property in conjunction with NetStream.bufferTime 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


Example
The following example dynamically creates a text field that displays information about the number of seconds that are currently in the buffer. The text field also displays the buffer length that the video is set to, and percentage of buffer that is filled.
this.createTextField("buffer_txt", this.getNextHighestDepth(), 10, 10, 300, 22);
buffer_txt.html = true;

var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
stream_ns.setBufferTime(3);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

var buffer_interval:Number = setInterval(checkBufferTime, 100, stream_ns);
function checkBufferTime(my_ns:NetStream):Void {
    var bufferPct:Number = Math.min(Math.round(my_ns.bufferLength/my_ns.bufferTime*100), 100);
    var output_str:String = "<textformat tabStops='[100,200]'>";
    output_str += "Length: "+my_ns.bufferLength+"\t"+"Time: "+my_ns.bufferTime+"\t"+"Buffer:"+bufferPct+"%";
    output_str += "</textformat>";
    buffer_txt.htmlText = output_str;
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

bufferTimeproperty 
bufferTime:Number  [read-only]

Player version: Flash Player 7 — Note: This property is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

The number of seconds assigned to the buffer by NetStream.setBufferTime(). The default value is .1(one-tenth of a second). To determine the number of seconds currently in the buffer, use NetStream.bufferLength.

Implementation
    public function get bufferTime():Number

See also


Example
The following example dynamically creates a text field that displays information about the number of seconds that are currently in the buffer. The text field also displays the buffer length that the video is set to, and percentage of buffer that is filled.
this.createTextField("buffer_txt", this.getNextHighestDepth(), 10, 10, 300, 22);
buffer_txt.html = true;

var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
stream_ns.setBufferTime(3);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

var buffer_interval:Number = setInterval(checkBufferTime, 100, stream_ns);
function checkBufferTime(my_ns:NetStream):Void {
    var bufferPct:Number = Math.min(Math.round(my_ns.bufferLength/my_ns.bufferTime*100), 100);
    var output_str:String = "<textformat tabStops='[100,200]'>";
    output_str += "Length: "+my_ns.bufferLength+"\t"+"Time: "+my_ns.bufferTime+"\t"+"Buffer:"+bufferPct+"%";
    output_str += "</textformat>";
    buffer_txt.htmlText = output_str;
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

bytesLoadedproperty 
bytesLoaded:Number  [read-only]

Player version: Flash Player 7

The number of bytes of data that have been loaded into the player. You can use this method in conjunction with NetStream.bytesTotal 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():Number

See also


Example
The following example creates a progress bar using the Drawing API and the bytesLoaded and bytesTotal properties that displays the loading progress of video1.flv into the video object instance called my_video. A text field called loaded_txt is dynamically created to display information about the loading progress as well.
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22);
this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());
progressBar_mc.createEmptyMovieClip("bar_mc", progressBar_mc.getNextHighestDepth());
with (progressBar_mc.bar_mc) {
    beginFill(0xFF0000);
    moveTo(0, 0);
    lineTo(100, 0);
    lineTo(100, 10);
    lineTo(0, 10);
    lineTo(0, 0);
    endFill();
    _xscale = 0;
}
progressBar_mc.createEmptyMovieClip("stroke_mc", progressBar_mc.getNextHighestDepth());
with (progressBar_mc.stroke_mc) {
    lineStyle(0, 0x000000);
    moveTo(0, 0);
    lineTo(100, 0);
    lineTo(100, 10);
    lineTo(0, 10);
    lineTo(0, 0);
}

var loaded_interval:Number = setInterval(checkBytesLoaded, 500, stream_ns);
function checkBytesLoaded(my_ns:NetStream) {
    var pctLoaded:Number = Math.round(my_ns.bytesLoaded/my_ns.bytesTotal*100);
    loaded_txt.text = Math.round(my_ns.bytesLoaded/1000)+" of "+Math.round(my_ns.bytesTotal/1000)+" KB loaded ("+pctLoaded+"%)";
    progressBar_mc.bar_mc._xscale = pctLoaded;
    if (pctLoaded>=100) {
    clearInterval(loaded_interval);
    }
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

bytesTotalproperty 
bytesTotal:Number  [read-only]

Player version: Flash Player 7

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

Implementation
    public function get bytesTotal():Number

See also


Example
The following example creates a progress bar using the Drawing API and the bytesLoaded and bytesTotal properties that displays the loading progress of video1.flv into the video object instance called my_video. A text field called loaded_txt is dynamically created to display information about the loading progress as well.
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22);
this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());
progressBar_mc.createEmptyMovieClip("bar_mc", progressBar_mc.getNextHighestDepth());
with (progressBar_mc.bar_mc) {
    beginFill(0xFF0000);
    moveTo(0, 0);
    lineTo(100, 0);
    lineTo(100, 10);
    lineTo(0, 10);
    lineTo(0, 0);
    endFill();
    _xscale = 0;
}
progressBar_mc.createEmptyMovieClip("stroke_mc", progressBar_mc.getNextHighestDepth());
with (progressBar_mc.stroke_mc) {
    lineStyle(0, 0x000000);
    moveTo(0, 0);
    lineTo(100, 0);
    lineTo(100, 10);
    lineTo(0, 10);
    lineTo(0, 0);
}

var loaded_interval:Number = setInterval(checkBytesLoaded, 500, stream_ns);
function checkBytesLoaded(my_ns:NetStream) {
    var pctLoaded:Number = Math.round(my_ns.bytesLoaded/my_ns.bytesTotal*100);
    loaded_txt.text = Math.round(my_ns.bytesLoaded/1000)+" of "+Math.round(my_ns.bytesTotal/1000)+" KB loaded ("+pctLoaded+"%)";
    progressBar_mc.bar_mc._xscale = pctLoaded;
    if (pctLoaded>=100) {
    clearInterval(loaded_interval);
    }
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

checkPolicyFileproperty 
public var checkPolicyFile:Boolean

Language version: ActionScript 2.0
Player version: Flash Player 9

Specifies whether Flash Player should attempt to download a policy file from the loaded FLV file's server before beginning to load the FLV file itself. This flag is applicable when you are using a NetStream for progressive video download (standalone FLV files), but not when you are using a NetStream to obtain an RTMP asset.

Set this flag to true when you are loading an FLV video file from outside the calling SWF file's own domain and you expect to access the content of that image using BitmapData.draw(). If you attempt this operation without having specified checkPolicyFile at loading time, you may encounter a security error because the needed policy file has not been downloaded yet.

When you call NetStream.play() with checkPolicyFile set to true, Flash Player does not begin downloading the object specified in your call to play() until it has either successfully downloaded a relevant policy file or discovered that no such policy file exists. Flash Player first considers policy files that have already been downloaded, then attempts to download any pending policy files specified in calls to System.security.loadPolicyFile(), then attempts to download a policy file from the default location that corresponds to the URL you passed to play(), which is /crossdomain.xml on the same server as that URL. In all cases, Flash Player requires that the given policy file exists on its server, that the file provides access to the object at the URL you passed to play() by virtue of the policy file's location, and that the file permits access by the domain of the calling SWF by virtue of one or more <allow-access-from> tags.

If you set checkPolicyFile to true, Flash Player waits until policy file completion to begin the main download that you specify in play(). Thus, as long as the policy file that you need exists, as soon as you have received any onMetaData or onStatus events from your NetStream, the policy file download is complete and you can safely begin performing operations that require the policy file.

If you set checkPolicyFile to true, and no relevant policy file is found, you do not receive any error indication until you attempt an operation that throws a SecurityError exception.

Try to avoid setting checkPolicyFile to true if you will not be needing pixel-level access to the video that you are loading. Checking for a policy file in this case is wasteful because it may delay the start of your download and may consume network bandwidth unnecessarily.

Be careful with checkPolicyFile if you are downloading an FLV file from a URL that may use server-side HTTP redirects. Flash Player always attempts 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, then the initially downloaded policy file(s) might not be applicable to the FLV file's final URL, which is the URL that matters in security decisions.

currentFpsproperty 
currentFps:Number  [read-only]

Player version: Flash Player 7 — Note: This property is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

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

Example
The following example creates a text field that displays the current number of frames per second that video1.flv displays.
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

this.createTextField("fps_txt", this.getNextHighestDepth(), 10, 10, 50, 22);
fps_txt.autoSize = true;
var fps_interval:Number = setInterval(displayFPS, 500, stream_ns);
function displayFPS(my_ns:NetStream) {
    fps_txt.text = "currentFps (frames per second): "+Math.floor(my_ns.currentFps);
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

liveDelayproperty 
liveDelay:Number  [read-only]

Language version: ActionScript 2.0
Player version: Flash Player 6

The number of seconds of data in the specified subscribing stream’s buffer in live (unbuffered) mode. This property indicates the current network transmission delay (lag time). This property is intended primarily for use with Flash Media Server.

Implementation
    public function get liveDelay():Number
maxPauseBufferTimeproperty 
public var maxPauseBufferTime:Number

Language version: ActionScript 2.0
Player version: Flash Player 10

Specifies the maximum number of seconds to buffer messages during pause mode. The default value is 60 seconds or twice the value of NetStream.bufferTime on each pause, whichever is higher.

As soon as the value of NetStream.bufferLength reaches this limit, buffering stops.

See also

timeproperty 
time:Number  [read-only]

Player version: Flash Player 7 — Note: This property is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

The position of the playhead, in seconds.

Implementation
    public function get time():Number

See also


Example
The following example displays the current position of the playhead in a dynamically created text field called time_txt. Select New Video from the Library options menu to create a video object instance, and give it an instance name my_video. Create a new video object called my_video. Add the following ActionScript to your FLA or AS file:
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");
//
stream_ns.onStatus = function(infoObject:Object) {
    statusCode_txt.text = infoObject.code;
};

this.createTextField("time_txt", this.getNextHighestDepth(), 10, 10, 100, 22);
time_txt.text = "LOADING";

var time_interval:Number = setInterval(checkTime, 500, stream_ns);
function checkTime(my_ns:NetStream) {
    var ns_seconds:Number = my_ns.time;
    var minutes:Number = Math.floor(ns_seconds/60);
    var seconds = Math.floor(ns_seconds%60);
    if (seconds<10) {
    seconds = "0"+seconds;
    }
    time_txt.text = minutes+":"+seconds;
}

If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method, which is used in this example.

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

Player version: Flash Player 7 — Note: This class is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

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

Parameters
connection:NetConnection — A NetConnection object.

See also


Example
The following code first constructs a new NetConnection object, connection_nc, and uses it to construct a new NetStream object called stream_ns. Select New Video from the Library options menu to create a video object instance, and give it an instance name my_video. Create a new video object called my_video. Then add the following ActionScript to your FLA or AS file:
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

Method detail
attachAudio()method
public function attachAudio(theMicrophone:Microphone):Void

Language version: ActionScript 2.0
Player version: Flash Player 6

Specifies an audio stream to be sent over the NetStream object. This method is available only to the publisher of the specified stream.

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

For more information, see the Flash Media Server documentation.

Parameters
theMicrophone:Microphone — The source of the audio to be transmitted, as a Microphone object.

See also

attachVideo()method 
public function attachVideo(theCamera:Camera, snapshotMilliseconds:Number):Void

Language version: ActionScript 2.0
Player version: Flash Player 6

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

For more information, see the Flash Media Server documentation.

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:Number — Optional integer parameter that specifies whether the video stream is continuous, a single frame, or a series of single frames used to create time-lapse photography. If this parameter is omitted, Flash Player captures all video until you pass null for the theCamera parameter. If you pass 0, Flash Player captures only a single video frame. Use 0 to transmit "snapshots" in a preexisting stream. If you pass a positive number, Flash Player captures a single video frame and then appends a pause of snapShotMilliseconds as a "trailer" on the snapshot. This creates time-lapse photography effects.

See also

close()method 
public function close():Void

Player version: Flash Player 7 — Note: This method is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

Stops playing all data on the stream, sets the NetStream.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 using HTTP. Although Flash Player will delete the local copy of the FLV file that it creates, a copy of the video may persist in the browser's cache directory. If complete prevention of caching or local storage of the FLV file is required, use Flash Media Server.

See also


Example
The following onDisconnect() function closes a connection and deletes the temporary copy of video1.flv that was stored on the local disk when you click the button called close_btn:
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");

close_btn.onRelease = function(){
    stream_ns.close();
};

getInfo()method 
public function getInfo():Object

Language version: ActionScript 2.0
Player version: Flash Player 10

Returns an object containing various Quality of Service (QOS) statistics related to a NetStream object and its underlying streaming buffer for audio, video, and data. This method provides a snapshot of the current quality of service. For a list of the properties in the returned object, see the Flash Media Server documentation.

Returns
Object — The info object.
pause()method 
public function pause([flag:Boolean]):Void

Player version: Flash Player 7 — Note: This method is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

Pauses or resumes playback of a stream.

The first time you call this method (without sending a parameter), it pauses play; the next time, it resumes play. You might want to attach this method to a button that the user presses to pause or resume playback.

Parameters
flag:Boolean [optional] — A Boolean value specifying whether to pause play (true) or resume play (false). If you omit this parameter, NetStream.pause() acts as a toggle: the first time it is called on a specified stream, it pauses play, and the next time it is called, it resumes play.

See also


Example
The following examples illustrate some uses of this method:
my_ns.pause(); // pauses play first time issued
my_ns.pause(); // resumes play
my_ns.pause(false); // no effect, play continues
my_ns.pause(); // pauses play

play()method 
public function play(name:Object, start:Number, len:Number, reset:Object):Void

Player version: Flash Player 7 — Note: This method is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

Begins playback of an external video (FLV) file. To view video data, you must call a Video.attachVideo() method; audio being streamed with the video, or an FLV file that contains only audio, is played automatically.

You cannot connect to commonly reserved ports when you are using a null NetConnection. For a complete list of blocked ports, see the system.Security.loadPolicyFile() entry.

If you want to control the audio associated with an FLV file, you can use MovieClip.attachAudio() to route the audio to a movie clip; you can then create a Sound object to control some aspects of the audio. For more information, see MovieClip.attachAudio().

If the FLV file can't be found, the NetStream.onStatus event handler is invoked. If you want to stop a stream that is currently playing, use NetStream.close().

You can play local FLV files that are stored in the same directory as the SWF file or in a subdirectory; you can't navigate to a higher-level directory. For example, if the SWF file is located in a directory named /training, and you want to play a video stored in the /training/videos directory, you would use the following syntax:

my_ns.play("videos/videoName.flv");

To play a video stored in the /training directory, you would use the following syntax:

my_ns.play("videoName.flv");

When using this method, consider the Flash Player security model.

For more information related to security, see the following:

Parameters
name:Object — The name of an FLV file to play, in quotation marks. Both http:// and file:// formats are supported; the file:// location is always relative to the location of the SWF file.
 
start:Number
 
len:Number
 
reset:Object

See also


Example
The following example illustrates some ways to use the NetStream.play() command. You can play a file that is on a user's computer. The joe_user directory is a subdirectory of the directory where the SWF is stored. And, you can play a file on a server:
// Play a file that is on the user's computer.
my_ns.play("file://joe_user/flash/videos/lectureJune26.flv");

// Play a file on a server.
my_ns.play("http://someServer.someDomain.com/flash/video/orientation.flv");

play2()method 
public function play2(playParam:Object):Void

Language version: ActionScript 2.0
Player version: Flash Player 10

Plays streaming audio, video, and text messages being published to Flash Media Server, or plays a recorded stream stored on the server.

This method is available only to clients subscribed to the specified stream, not to the publisher of the stream.

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 the server to switch to a different media file. The transition occurs seamlessly in the client application.

Use the play2() method to switch to streams with the same content encoded at different bit rates or to swap streams in a playlist. This method lets an application adapt to changing network conditions or clients with different capabilities.

Supported file formats are FLV, MP3, ID3, and MPEG-4 based files such as F4V or MP4.

Parameters
playParam:Object — An object that contains properties describing the media to play. For details about the properties in this object, see the Flash Media Server documentation.

See also

publish()method 
public function publish(name:Object, type:String):Void

Player version: Flash Player 6; — MP4, F4V recording support is available in Flash Media Server 3.5

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

When you publish a stream, you can record or append it to a file in FLV, MP4, or F4V format. To record in MP4 or F4V format, prefix the stream name with "mp4:" and specify the file extension. The recorded filename is the name you pass in the name parameter. For example, ns.publish("mp4:streamName.f4v", "record") creates the file "streamName.f4v". The code ns.publish("mp4:streamName2.mp4", "record") creates the file "streamName2.mp4". You do not need to specify a file extension or a prefix when recording in FLV format.

The NetStream.publish() method does not play streams. To play streams, use the NetStream.play() method.

To report status, this method invokes NetStream.onStatus().

For more information about NetStream.publish(), see the Flash Media Server documentation.

Parameters
name:Object — A string parameter that identifies a stream. To subscribe to this stream, pass this name to the NetStream.play() method.
 
type:String — An optional string parameter that specifies how to publish the stream. Valid values are "record", "append", and "live". If the value is "record", the stream is published and a new file is created or, if the file exists, it is overwritten. In Flash Player 10 and later, the "record" value supports F4V (MPEG-4 based) content. If the value is "append", the stream is published and the incoming data is appended to the end of the existing file. If the value is "live", data is published but not recorded. If the value is "live" and a file with the same name exists on the server, the server deletes the file, unless the file is read-only. The default is "live".

See also

receiveAudio()method 
public function receiveAudio(receive:Boolean):Void

Language version: ActionScript 2.0
Player version: Flash Player 6

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

You can call this method before or after you call the NetStream.play() method and begin receiving the stream.

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

For more information, see the Flash Media Server documentation.

Parameters
receive:Boolean — A Boolean value that specifies whether incoming audio plays on the specified stream. The default value is true.

See also

receiveVideo()method 
public function receiveVideo(receive:Boolean):Void

Language version: ActionScript 2.0
Player version: Flash Player 6

Specifies whether incoming video plays on the specified stream or specifies the frame rate of the video. If called with true or false, specifies whether to play incoming video on the stream.

Note: You can also call receiveVideo(FPS:Number) with a numeric parameter specifying the frame rate per second (FPS) to play the incoming video. The default FPS rate is the frame rate of the file or live stream being played. If you call this method with a frame rate parameter after calling NetStream.receiveVideo(false), an implicit call to NetStream.receiveVideo(true) is issued. For details on the receiveVideo(FPS:Number) version of this method, see the Flash Media Server documentation.

This method is available only to clients subscribed to the specified stream, not to the stream’s publisher.

Parameters
receive:Boolean — A Boolean value that specifies whether incoming video plays on the specified stream. See note on alternate syntax supporting a frame rate parameter.

See also

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

Player version: Flash Player 7 — Note: This method is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

Seeks the keyframe closest to the specified number of seconds from the beginning of the stream. The stream resumes playing when it reaches the specified location in the stream.

Parameters
offset:Number — The approximate time value, in seconds, to move to in an FLV file. The playhead moves to the previous keyframe, or with Flash Media Server and the proper setting of EnhancedSeek in application.xml, generates a keyframe.

See also


Example
The following example illustrates some ways to use NetStream.seek() You can return to the beginning of the stream, move to a location 30 seconds from the beginning of the stream, and move backwards three minutes from the current location:
// Return to the beginning of the stream
my_ns.seek(0);

// Move to a location 30 seconds from the beginning of the stream
my_ns.seek(30);

// Move backwards three minutes from current location
my_ns.seek(my_ns.time - 180);

send()method 
public function send(handlerName:String, [optionalArgs:]):Void

Language version: ActionScript 2.0
Player version: Flash Player 6

Broadcasts a message on the specified stream to all subscribing clients. This method is available only to the publisher of the specified stream. To process and respond to the message, create a handler in the format my_ns.handlerName.

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

You can also use the send() method to add keyframes of metadata to live streams or to clear metadata from a stream.

For more information, see the Flash Media Server documentation.

Parameters
handlerName:String — A string that identifies the message, which is also the name of the handler to receive the message. Do not use a reserved term for a handler name. The handler name must be only one level deep (that is, it can’t be of the form parent/child) and is relative to the stream object.
 
optionalArgs: [optional] — The arguments to the handler. They can be of any type.
setBufferTime()method 
public function setBufferTime(bufferTime:Number):Void

Player version: Flash Player 7 — Note: This method is also supported in Flash Player 6 when used with Flash Media Server. For more information, see the Flash Media Server documentation.

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

Parameters
bufferTime:Number — The number of seconds of data to be buffered before Flash begins displaying data. The default value is 0.1 (one-tenth of a second).

See also


Example
See the example for NetStream.bufferLength.

Event detail
onCuePointevent handler

public onCuePoint = function(infoObject:Object) {}

Player version: Flash Player 8

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. This lets you synchronize other actions in your application with video playback events.

There are two types of cue points that can be embedded in an FLV file.

The onCuePoint() event handler receives an object with these properties:

PropertyDescription
nameThe name given to the cue point when it was embedded in the FLV file.
timeThe time in seconds at which the cue point occurred in the video file during playback.
typeThe type of cue point that was reached, either "navigation" or "event".
parametersA associative array of name/value pair strings specified for this cue point. Any valid string can be used for the parameter name or value.

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 handler also retrieves information about the cue points in a video file. However the onMetaData() event handler gets information about all of the cue points before the video begins playing. The onCuePoint() event handler receives information about a single cue point at the time specified for that cue point during playback.

Generally if you want your code to respond to a specific cue point at the time it occurs you should use the onCuePoint() event handler to trigger some action in your code.

You can use the list of cue points provided to the onMetaData() event handler to let your 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.

Parameters
infoObject:Object — An object containing the name, time, type, and parameters for the cue point.

Example
The code in this example starts by creating new NetConnection and NetStream objects. Then it defines the onCuePoint() handler for the NetStream object. The handler cycles through each named property in the infoObject object and prints the property's name and value. When it finds the property named parameters it cycles through each parameter name in the list and prints the parameter name and value.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);

ns.onCuePoint = function(infoObject:Object) 
{
    trace("onCuePoint:");
    for (var propName:String in infoObject) {
        if (propName != "parameters")
        {
            trace(propName + " = " + infoObject[propName]);
        }
        else
        {
            trace("parameters =");
            if (infoObject.parameters != undefined) {
                for (var paramName:String in infoObject.parameters)
                {
                    trace("   " + paramName + ": " + infoObject.parameters[paramName]);
                }
            }
            else
            {
                trace("undefined");
            }
        }        
    }
    trace("---------");    
}

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

This causes the following information to be displayed:

      onCuePoint:
      parameters =
         lights: beginning
      type = navigation
      time = 0.418
      name = point1
      ---------
      onCuePoint:
      parameters =
         lights: middle
      type = navigation
      time = 7.748
      name = point2
      ---------
      onCuePoint:
      parameters =
         lights: end
      type = navigation
      time = 16.02
      name = point3
      ---------

The parameter name "lights" is an arbitrary name used by the author of the example video. You can give cue point parameters any name you want.

See also

onMetaDataevent handler 

public onMetaData = function(infoObject:Object) {}

Player version: Flash Player 7

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

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

This handler 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 will not always match the value of the NetStream.time property when the playhead is at the end of the video stream.

Parameters
infoObject:Object — An object containing one property for each metadata item.

Example
The code in this example starts by creating new NetConnection and NetStream objects. Then it defines the onMetaData() handler for the NetStream object. The handler cycles through each named property in the infoObject object and prints the property's name and value.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);

ns.onMetaData = function(infoObject:Object) {
    for (var propName:String in infoObject) {
        trace(propName + " = " + infoObject[propName]);
    }
};

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

This causes the following information to be displayed:

canSeekToEnd = true
      videocodecid = 4
      framerate = 15
      videodatarate = 400
      height = 215
      width = 320
      duration = 7.347

The list of properties will vary depending on the software that was used to encode the FLV file.

See also

onPlayStatusevent handler 

public onPlayStatus = function(infoObject:Object) {}

Language version: ActionScript 2.0
Player version: Flash Player 6

Invoked when a NetStream object has completely played a stream. To respond to this event, create a function to process the information object sent by the server.

For more information, see the Flash Media Server documentation.

Parameters
infoObject:Object — An object with code and level properties that provide information about the play status of a NetStream object. Code properties may be NetStream.Play.Complete, NetStream.Play.TransitionComplete, and NetStream.Play.Switch. NetStream.Play.TransitionComplete was added in Flash Player 10.

See also

onStatusevent handler 

public onStatus = function(infoObject:Object) {}

Player version: Flash Player 6

Invoked every time a status change or error is posted for the NetStream object. If you want to respond to this event handler, you must create a function to process the information object.

The information object has a code property containing a string that describes the result of the onStatus handler, and a level property containing a string that is either status or error.

In addition to this onStatus handler, Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

The following events notify you when certain NetStream activities occur.

Code property Level property Meaning
NetStream.Buffer.Empty status Data is not being received quickly enough to fill the buffer. Data flow will be interrupted until the buffer refills, at which time a NetStream.Buffer.Full message will be sent and the stream will begin playing again.
NetStream.Buffer.Full status The buffer is full and the stream will begin playing.
NetStream.Buffer.Flush status Data has finished streaming, and the remaining buffer will be emptied.
NetStream.Failed error An error has occurred for a reason other than those listed. Added in Flash Player 10.
NetStream.Play.Start status Playback has started.
NetStream.Play.Stop status Playback has stopped.
NetStream.Play.Transition status Flash Media Server only. The stream transitions to another as a result of a successful NetStream.play2() call. If the switch does not succeed, the server sends a NetStream.Play.Failed event instead. Added in Flash Player 10.
NetStream.Play.StreamNotFound error The FLV passed to the play() method can't be found.
NetStream.Seek.InvalidTime error For video downloaded with progressive download, the user has tried to seek or play past the end of the video data that has downloaded thus far, or past the end of the video once the entire file has downloaded. The Error.message.details property contains a time code that indicates the last valid position to which the user can seek. See Error.message property.
NetStream.Seek.Notify status The seek operation is complete.

If you consistently see errors regarding the buffer, you should try changing the buffer using the NetStream.setBufferTime() method.

For information on additional status codes, see the Flash Media Server documentation.

Parameters
infoObject:Object — A parameter defined according to the status message or error message.

Example
The following example displays data about the stream in the Output panel: The following example writes data about the stream to the log file:
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
my_video.attachVideo(stream_ns);
stream_ns.play("video1.flv");
stream_ns.onStatus = function(infoObject:Object) {
        trace("NetStream.onStatus called: ("+getTimer()+" ms)");
        for (var prop in infoObject) {
            trace("\t"+prop+":\t"+infoObject[prop]);
        }
        trace("");
};

See also

onTextDataevent handler 

public onTextData = function(textData:Object) {}

Language version: ActionScript 2.0
Player version: Flash Player 9 — Update 3

Invoked when a NetStream object receives text data embedded in a media file that is playing. To respond to this event, create a function to process the text data object sent by the server.

The text data is in UTF-8 format and can contain information about formatting based on the 3GPP timed text specification. For more information, see the 3GPP website.

For more information, see the Flash Media Server documentation.

Parameters
textData:Object — An object containing one property for each piece of text data.

See also

onXMPDataevent handler 

public onXMPData = function(data:Object) {}

Language version: ActionScript 2.0
Player version: Flash Player 10

Invoked when a NetStream object receives receives information specific to Adobe Extensible Metadata Platform (XMP) metadata embedded in the media being played. To respond to this event, create a function to process the data object sent by the server.

Adobe® Creative Suite® supports the creation and embedding of XMP metadata in files. Through the onXMP() callback method, Flash Media Server can deliver the XMP data embedded in FLV and F4V files.

Flash Media Server delivers but does not parse the XMP data embedded in a media file.

To parse the XMP data in the file, use XML parsing technology, for example, the XML class in ActionScript.

Parameters
data:Object — An information object that contains the entire XMP message in the media file..

See also