MACROMEDIA MEDIA SERVER 2 Reference

Client-Side ActionScript Language Reference for Flash Media Server 2
Trademarks
1 Step RoboPDF, ActiveEdit, ActiveTest, Authorware, Blue Sky Software, Blue Sky, Breeze, Breezo, Captivate, Central, ColdFusion, Contribute, Database Explorer, Director, Dreamweaver, Fireworks, Flash, FlashCast, FlashHelp, Flash Lite, FlashPaper, Flash Video Encoder, Flex, Flex Builder, Fontographer, FreeHand, Generator, HomeSite, JRun, MacRecorder, Macromedia, MXML, RoboEngine, RoboHelp, RoboInfo, RoboPDF, Roundtrip, Roundtrip HTML, Shockwave, SoundEdit, Studio MX, UltraDev, and WebHelp are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
Sorenson™ Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Copyright © 2002-2005 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without written approval from Macromedia, Inc. Notwithstanding the foregoing, the owner or authorized user of a valid copy of the software with which this manual was provided may print out one copy of this manual from an electronic version of this manual for the sole purpose of such owner or authorized user learning to use such software, provided that no part of this manual may be printed out, reproduced, distributed, resold, or transmitted for any other purposes, including, without limitation, commercial purposes, such as selling copies of this documentation or providing paid-for support services.
Acknowledgments
Project Management: Suzanne Smith
Writing: Jody Bleyle
Managing Editor: Rosana Francescato
Editing: Geta Carlson
Production Management: Patrice O’Neill
Media Design and Production: Adam Barnett, Aaron Begley, Mario Reynoso, Paul Benkman, John Franics
Special thanks to Erick Vera and the Flash Media Server engineering and QA teams.
First Edition: October 2005
Macromedia, Inc. 601 Townsend St.
San Francisco, CA 94103
Contents
Chapter 1: Client-Side ActionScript Language Reference. . . . . . . 5
ActionScript classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
ActionScript elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Camera class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Microphone class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
MovieClip class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
NetConnection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
NetStream class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76
SharedObject class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
System class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Video class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
Appendix A: Client-Side Information Objects . . . . . . . . . . . . . . .149
Camera information objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
LocalConnection information objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Microphone information objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
NetConnection information objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152
NetStream information objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153
SharedObject information objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156
3
4Contents
CHAPTER 1
Client-Side ActionScript Language Reference
Macromedia Flash Media Server provides two application program interfaces (APIs): a Client­Side Media ActionScript API and a Server-Side Media ActionScript API. This guide explains the client-side API.
This document is designed to be used in combination with the ActionScript documentation included with Macromedia Flash. Refer to the Flash documentation for general scripting information. Use this document to add Flash Media Server functionality to your Flash applications.
For additional information about developing applications for Flash Media Server and to understand how objects created on the client-side are paired with those on the server-Rside, see Developing Media Applications.
NOTE
Most sample code in this document uses ActionScript 2.0 syntax.
1
ActionScript classes
The following table lists all the classes in this guide, Client-Side ActionScript Language Reference for Flash Media Server 2:
ActionScript class Description
Camera class Lets you capture video from a video camera attached to the
computer that is running Macromedia Flash Player.
Microphone class Lets you capture audio from a microphone attached to the
computer that is running Flash Player.
MovieClip class Lets you specify whether an audio source is to be played locally
(Microphone object) or streamed from Flash Media Server (NetStream object).
5
ActionScript class Description
NetConnection class Manages a bidirectional connection between Flash Player and a
server, which lets you connect to Flash Remoting or to Flash Media Server.
NetStream class Opens a one-way streaming connection between Flash Player
and Flash Media Server through a connection made available by a NetConnection object.
SharedObject class Allows real-time data sharing between multiple client SWF files
and objects that are persistent on the local or remote location.
System class The System class contains properties related to certain
operations that take place on the user's computer, such as operations with shared objects, local settings for cameras and microphones, and use of the Clipboard.
Video class Lets you display live or recorded streaming video on the Stage
without embedding it in your SWF file.
ActionScript elements
Entries in this document are alphabetical by class name and then by method, property, or event handler name. The following table lists all classes, methods, properties, and event handlers individually in alphabetical order.
ActionScript element See entry
activityLevel
attachAudio
attachVideo
bandwidth
bufferLength
bufferTime
call
clear
close
connect
currentFps
data
Camera.activityLevel
MovieClip.attachAudio()
NetStream.attachVideo()
Camera.bandwidth
NetStream.bufferLength
NetStream.bufferTime
NetConnection.call()
SharedObject.clear()
NetConnection.close() SharedObject.close()
NetConnection.connect()
Camera.currentFps
SharedObject.data
, Microphone.activityLevel
, NetStream.attachAudio()
, Video.attachVideo()
, Video.clear()
, NetStream.close(),
, SharedObject.connect()
, NetStream.currentFps
6 Client-Side ActionScript Language Reference
ActionScript element See entry
deblocking
flush
fps
gain
get
getLocal
getRemote
getSize
height
index
isConnected
keyFrameInterval
loopback
liveDelay
motionLevel
Video.deblocking
SharedObject.flush()
Camera.fps
Microphone.gain
Camera.get()
SharedObject.getLocal()
SharedObject.getRemote()
SharedObject.getSize()
Camera.height
Camera.index
NetConnection.isConnected
Camera.keyFrameInterval
Camera.loopback
NetStream.liveDelay
Camera.motionLevel
, Microphone.get()
, Video.height
, Microphone.index
motionTimeOut
muted
name
names
onActivity
onCuePoint
onMetaData
onPlayStatus
onStatus
onSync
pause
play
publish
quality
Camera.motionTimeOut
Camera.muted
Camera.name
Camera.names
Camera.onActivity
NetStream.onCuePoint
NetStream.onMetaData
NetStream.onPlayStatus
Camera.onStatus NetStream.onStatus, SharedObject.onStatus
SharedObject.onSync
NetStream.pause()
NetStream.play()
NetStream.publish()
Camera.quality
, Microphone.muted
, Microphone.name
, Microphone.names
, Microphone.onActivity
, Microphone.onStatus, NetConnection.onStatus,
ActionScript elements 7
ActionScript element See entry
rate
receiveAudio
receiveVideo
seek
send
setBufferTime
setFps
setGain
setKeyFrameInterval
setLoopback
setMode
setMotionLevel
setQuality
setRate
setSilenceLevel
Microphone.rate
NetStream.receiveAudio()
NetStream.receiveVideo()
NetStream.seek()
NetStream.send()
NetStream.setBufferTime()
SharedObject.setFps()
Microphone.setGain()
Camera.setKeyFrameInterval()
Camera.setLoopback()
Camera.setMode()
Camera.setMotionLevel()
Camera.setQuality()
Microphone.setRate()
Microphone.setSilenceLevel()
, SharedObject.send()
setUseEchoSuppression
showSettings
silenceLevel
silenceTimeout
smoothing
time
uri
useCodepage
useEchoSuppression
width
Microphone.setUseEchoSuppression()
System.showSettings()
Microphone.silenceLevel
Microphone.silenceTimeout
Video.smoothing
NetStream.time
NetConnection.uri
System.useCodepage
Microphone.useEchoSuppression
Camera.width
Camera class
Availability
Flash Player 6.
Flash Media Server (not required).
, Video.width
8 Client-Side ActionScript Language Reference
The Camera class lets you capture video from a video camera attached to the computer that is running Macromedia Flash Player. When used with Flash Media Server, this class lets you transmit, display, and optionally record the video being captured. With these capabilities, you can develop media applications such as video conferencing, instant messaging with video, and so on. Flash provides similar audio capabilities; for more information, see the Microphone
class entry.
You can also use a Camera object without a server—for example, to monitor a video feed from a webcam attached to your local system.
NOTE
When a SWF file tries to access the camera returned by Camera.get(), Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the camera. (Make sure your Stage size is at least 215 x 138 pixels for the Camera class examples; this is the minimum size Flash requires to display the dialog box.) End users and administrative users may also disable camera access on a per-site or global basis.
To create or reference a Camera object, use the
Camera.get() method.
Method summary for the Camera class
Method Description
Camera.get() Returns a reference to a Camera object for capturing
video.
Camera.setKeyFrameInterval() Specifies which video frames are transmitted in full
instead of being interpolated by the video compression algorithm.
Camera.setLoopback() Specifies whether to use a compressed video stream for a
local view of what the camera is transmitting.
Camera.setMode() Sets aspects of the camera capture mode, including
height, width, and frames per second.
Camera.setMotionLevel() Specifies how much motion is required to invoke
Camera.onActivity(true).
Camera.setQuality() Sets the maximum amount of bandwidth per second or
the required picture quality of the current outgoing video feed.
Camera class 9
Property summary for the Camera class
Property (read-only) Description
Camera.activityLevel A numeric value from 0 to 100 that specifies the amount of
motion the camera is detecting.
Camera.bandwidth The maximum amount of bandwidth the current outgoing
video feed can use, in bytes.
Camera.currentFps The rate at which the camera is capturing data, in frames per
second.
Camera.fps The rate at which you would like the camera to capture data, in
frames per second.
Camera.height The current capture height, in pixels.
Camera.index The index of the camera, as reflected in the array returned by
Camera.names.
Camera.keyFrameInterval A number that specifies which video frames are transmitted in
full instead of being interpolated by the video compression algorithm.
Camera.loopback A Boolean value that specifies whether a local view of what
the camera is capturing is compressed or uncompressed.
Camera.motionLevel A numeric value from 0 to 100 that specifies the amount of
motion required to invoke
Camera.motionTimeOut The number of milliseconds between the time the camera
Camera.onActivity(true).
stops detecting motion and the time
Camera.onActivity(false) is invoked.
Camera.muted A Boolean value that specifies whether the user has allowed
or denied access to the camera.
Camera.name The name of the camera as specified by the camera hardware.
Camera.names Class property; an array of strings containing the names of all
available video capture devices, including video capture cards and cameras.
Camera.quality A number that specifies the current level of picture quality
based on the amount of compression being applied to each video frame.
Camera.width The current capture width, in pixels.
10 Client-Side ActionScript Language Reference
Event handler summary for the Camera class
Method Description
Camera.onActivity Invoked when the camera starts or stops detecting motion.
Camera.onStatus Invoked when the user allows or denies access to the camera.
Constructor for the Camera class
See Camera.get().
Camera.activityLevel
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public activityLevel : Number [read-only]
Description
Property (read-only); a numeric value that specifies the amount of motion the camera is detecting. Values range from 0 (no motion is being detected) to 100 (a large amount of motion is being detected). The value of this property can help you determine if you need to pass a setting to
If the camera is available but is not yet being used because neither
NetStream.attachVideo() has been called, this property is set to -1.
Camera.setMotionLevel().
Video.attachVideo() nor
If you are streaming only uncompressed local video—that is, you are not streaming the video within a NetStream object and you have not called property is set only if you have assigned a function to the
Camera.setLoopback()(true)—this
Camera.onActivity event handler.
Otherwise, it is undefined.
See also
Camera.motionLevel, Camera.onActivity, Camera.setMotionLevel()
Camera class 11
Camera.bandwidth
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public bandwidth : Number [read-only]
Description
Property (read-only); an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use, in bytes. A value of 0 means that Flash Video can use as much bandwidth as needed to maintain the desired frame quality.
To set this property, use
Camera.setQuality().
Example
The following example changes the maximum amount of bandwidth used by the camera feed. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name component instance to the Stage and give it the instance name
my_video. Add a NumericStepper
bandwidth_nstep. Then add
the following ActionScript to Frame 1 of the Timeline:
var bandwidth_nstep:mx.controls.NumericStepper; var my_video:Video; var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam); this.createTextField("bandwidth_txt", this.getNextHighestDepth(), 0, 0,
100, 22); bandwidth_txt.autoSize = true; this.onEnterFrame = function() { bandwidth_txt.text = "Camera is currently using "+my_cam.bandwidth+"
bytes ("+Math.round(my_cam.bandwidth/1024)+" KB) bandwidth."; }; // bandwidth_nstep.minimum = 0; bandwidth_nstep.maximum = 128; bandwidth_nstep.stepSize = 16; bandwidth_nstep.value = my_cam.bandwidth/1024; function changeBandwidth(evt:Object) { my_cam.setQuality(evt.target.value/1024, 0); } bandwidth_nstep.addEventListener("change", changeBandwidth);
12 Client-Side ActionScript Language Reference
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Camera.setQuality()
MovieClip.getNextHighestDepth() method.
Camera.currentFps
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public currentFps : Number [read-only]
Description
Property (read-only); the rate at which the camera is capturing data, in frames per second. This property cannot be set; however, you can use property—
Camera.fps—which specifies the maximum frame rate at which you would like
the camera to capture data.
Camera.setMode() to set a related
Example
The following example detects the rate in frames per second that the camera captures data, using the
currentFps property and a ProgressBar instance. Create a new video instance by
selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name the instance name
var my_video:Video; var fps_pb:mx.controls.ProgressBar; var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam); this.onEnterFrame = function() { fps_pb.setProgress(my_cam.fps-my_cam.currentFps, my_cam.fps); };
fps_pb.setStyle("fontSize", 10); fps_pb.setStyle("themeColor", "haloOrange"); fps_pb.labelPlacement = "top"; fps_pb.mode = "manual"; fps_pb.label = "FPS: %2 (%3%% dropped)";
my_video. Add a ProgressBar component instance to the Stage and give it fps_pb. Then add the following ActionScript to Frame 1 of the Timeline:
Camera class 13
See also
Camera.fps, Camera.setMode()
Camera.fps
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public fps : Number [read-only]
Description
Property (read-only); the maximum rate at which you want the camera to capture data, in frames per second. The maximum rate possible depends on the capabilities of the camera; that is, if the camera doesn’t support the value you set here, this frame rate will not be achieved.
To set a desired value for this property, use Camera.setMode().
To determine the rate at which the camera is currently capturing data, use
Camera.currentFps.
Example
The following example detects the rate in frames per second that the camera captures data, using the
currentFps property and a ProgressBar instance. Create a new video instance by
selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name the instance name
var my_video:Video; var fps_pb:mx.controls.ProgressBar; var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam); this.onEnterFrame = function() { fps_pb.setProgress(my_cam.fps-my_cam.currentFps, my_cam.fps); };
fps_pb.setStyle("fontSize", 10); fps_pb.setStyle("themeColor", "haloOrange"); fps_pb.labelPlacement = "top"; fps_pb.mode = "manual"; fps_pb.label = "FPS: %2 (%3%% dropped)";
NOTE
The setMode() method does not guarantee the requested fps setting; it sets the fps you requested or the fastest fps available.
my_video. Add a ProgressBar component instance to the Stage and give it fps_pb. Then add the following ActionScript to Frame 1 of the Timeline:
14 Client-Side ActionScript Language Reference
See also
Camera.currentFps, Camera.setMode()
Camera.get()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public static get([index:Number]) : Camera
NOTE
To assign the Camera object to a variable, use the following syntax:
var active_cam:Camera = Camera.get().
Parameters
index An optional zero-based integer that specifies which camera driver to get, as
determined from the array returned by (which is recommended for most applications), omit this parameter.
Camera.names. To get the default camera driver
Returns
If index is not specified, this method returns a reference to the default camera driver or, if
it is in use by another application, to the first available camera driver. (If there is more than one camera driver installed, the user may specify the default camera driver in the Flash Player Camera Settings panel.) If no camera drivers are available or installed, the method returns
If index is specified, this method returns a reference to the requested camera driver, or
null if it is not available.
Description
null.
Method; returns a reference to a Camera object for capturing video. To actually begin capturing the video, you must attach the Camera object either to a Video object (see
Video.attachVideo()) or to a NetStream object (see NetStream.attachVideo()). (The
NetStream object is available only with Flash Media Server.)
NOTE
The Camera.get() method returns a reference to a camera driver, not to a physical camera.
Camera class 15
Unlike objects that you create using the new constructor, multiple calls to Camera.get() reference the same camera driver. Thus, if your script contains the lines
cam1 = Camera.get() and cam2 = Camera.get(), both cam1 and cam2 reference the same
(default) camera driver.
In general, you shouldn’t pass a value for
index; simply use Camera.get() to return a
reference to the default camera driver. By means of the Camera settings panel (discussed later in this section), the user can specify the default camera driver Flash should use. If you pass a value for prefers. You might use
index, you might be trying to reference a camera driver other than the one the user
index in rare cases—for example, if your application is capturing video
from two cameras at the same time.
When a SWF file tries to access the camera returned by you issue
NetStream.attachVideo() or Video.attachVideo()—Flash Player displays a
Camera.get()—for example, when
Privacy dialog box that lets the user choose whether to allow or deny access to the camera. (Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash requires to display the dialog box.)
When the user responds to this dialog box, the
Camera.onStatus event handler returns an
information object that indicates the user’s response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use
Camera.muted.
The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing and selecting Settings. When the Privacy dialog box opens, the user selects Remember.
You can’t use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy dialog box for the user by using
System.showSettings(0). If the user selects
Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.
If
Camera.get() returns null, either the camera is in use by another application, or there are
no cameras installed on the system. To determine whether any cameras are installed, use
Camera.names.length. To display the Flash Player Camera Settings panel, which lets the
user choose the camera driver to be referenced by
System.showSettings(3).
16 Client-Side ActionScript Language Reference
Camera.get(), use
Scanning the hardware for cameras takes time. When Flash finds at least one camera, the hardware is not scanned again for the lifetime of the Flash Player instance. However, if Flash doesn’t find any cameras, it will scan each time
Camera.get() is called. This is helpful if a
user has forgotten to connect the camera; if your SWF file provides a Try Again button that calls
Camera.get(), Flash can find the camera without the user having to restart the
SWF file.
Example
The following example lets you select an active camera to use from a ComboBox instance. The current active camera is displayed in a Label instance. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name instance name name
cameras_cb. Then add the following ActionScript to Frame 1 of the Timeline:
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); var camera_lbl:mx.controls.Label; var cameras_cb:mx.controls.ComboBox; camera_lbl.text = my_cam.name; cameras_cb.dataProvider = Camera.names; function changeCamera():Void { my_cam = Camera.get(cameras_cb.selectedIndex); my_video.attachVideo(my_cam); camera_lbl.text = my_cam.name; } cameras_cb.addEventListener("change", changeCamera); camera_lbl.setStyle("fontSize", 9); cameras_cb.setStyle("fontSize", 9);
my_video. Add a Label component instance to the Stage and give it the
camera_lbl, and a ComboBox component instance and give it the instance
See also
Camera.index, Camera.muted, Camera.names, Camera.onStatus, Camera.setMode(), NetStream.attachVideo(), System.showSettings(), Video.attachVideo()
Camera class 17
Camera.height
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public height : Number [read-only]
Description
Property (read-only); the current capture height, in pixels. To set a value for this property, use
Camera.setMode().
Example
The following code displays the current width, height and FPS of a video instance in a Label component instance on the Stage. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name
my_video. Add a Label component instance to the Stage and give it the instance name dimensions_lbl. Then add the following ActionScript to Frame 1 of the Timeline:
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); var dimensions_lbl:mx.controls.Label; dimensions_lbl.setStyle("fontSize", 9); dimensions_lbl.setStyle("fontWeight", "bold"); dimensions_lbl.setStyle("textAlign", "center"); dimensions_lbl.text = "width: "+my_cam.width+", height: "+my_cam.height+",
FPS: "+my_cam.fps;
See also the example for Camera.setMode().
See also
Camera.setMode(), Camera.width
Camera.index
Availability
Flash Player 6.
Flash Media Server (not required).
18 Client-Side ActionScript Language Reference
Usage
active_cam.index
Description
Property (read-only); a zero-based integer that specifies the index of the camera, as reflected in the array returned by
Example
Camera.names.
The following example displays an array of cameras in a text field that is created at runtime, and tells you which camera you are currently using. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name instance name
var camera_lbl:mx.controls.Label; var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
camera_lbl.text = my_cam.index+". "+my_cam.name; this.createTextField("cameras_txt", this.getNextHighestDepth(), 25, 160,
160, 80); cameras_txt.html = true; cameras_txt.border = true; cameras_txt.wordWrap = true; cameras_txt.multiline = true; for (var i = 0; i<Camera.names.length; i++) { cameras_txt.htmlText += "<li><u><a
href=\"asfunction:changeCamera,"+i+"\">"+Camera.names[i]+"</a></u></
li>"; } function changeCamera(index:Number) { my_cam = Camera.get(index); my_video.attachVideo(my_cam); camera_lbl.text = my_cam.index+". "+my_cam.name; }
my_video. Add a Label component instance to the Stage and give it the camera_lbl. Then add the following ActionScript to Frame 1 of the Timeline:
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Camera.get(), Camera.names
MovieClip.getNextHighestDepth() method.
Camera class 19
Camera.keyFrameInterval
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public keyFrameInterval : Number [read-only]
Description
Property (read-only); a number that specifies which video frames are transmitted in full (called keyframes) instead of being interpolated by the video compression algorithm. The default value is 15 (every 15th frame is a keyframe).
See also
Camera.setKeyFrameInterval()
Camera.loopback
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public loopback : Boolean [read-only]
Description
Property (read-only); a Boolean value that specifies whether a local view of what the camera is capturing is compressed and decompressed as it would be for live transmission using Flash Media Server (
true) or uncompressed (false). The default value is false.
To set this value, use Camera.setLoopback(). To set the amount of compression used when this property is
Example
true, use Camera.setQuality().
See the example for Camera.setLoopback().
See also
Camera.setLoopback(), Camera.setQuality()
20 Client-Side ActionScript Language Reference
Camera.motionLevel
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public motionLevel : Number [read-only]
Description
Property (read-only); a numeric value that specifies the amount of motion required to invoke
Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.
Video can be displayed regardless of the value of the information, see
Camera.setMotionLevel().
motionLevel property. For more
Example
The following example continually detects the motion level of a camera feed. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name and give it the instance name
motionLevel_nstep, and a ProgressBar with the instance name motion_pb. Then add the
my_video. Add a Label component instance to the Stage
motionLevel_lbl, a NumericStepper with the instance name
following ActionScript to Frame 1 of the Timeline:
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
// Configure the ProgressBar component instance. var motion_pb:mx.controls.ProgressBar; motion_pb.mode = "manual"; motion_pb.label = "Motion: %3%%";
var motionLevel_lbl:mx.controls.Label; // Configure the NumericStepper component instance. var motionLevel_nstep:mx.controls.NumericStepper; motionLevel_nstep.minimum = 0; motionLevel_nstep.maximum = 100; motionLevel_nstep.stepSize = 5; motionLevel_nstep.value = my_cam.motionLevel;
/* Continuously update the progress of the ProgressBar component instance to the activityLevel of the current Camera instance, which is defined in my_cam. */
Camera class 21
this.onEnterFrame = function() { motion_pb.setProgress(my_cam.activityLevel, 100); };
/* When the level of activity goes above or below the number defined in Camera.motionLevel, trigger the onActivity event handler. */ my_cam.onActivity = function(isActive:Boolean) { /* If isActive equals true, set the themeColor variable to "haloGreen".
Otherwise set the themeColor to "haloOrange".*/ var themeColor:String = (isActive) ? "haloGreen" : "haloOrange"; motion_pb.setStyle("themeColor", themeColor); };
function changeMotionLevel() {
/* Set the motionLevel property for my_cam Camera
instance to the value of the NumericStepper
component instance. Maintain the current
motionTimeOut value of the my_cam Camera instance.*/ my_cam.setMotionLevel(motionLevel_nstep.value, my_cam.motionTimeOut); } motionLevel_nstep.addEventListener("change", changeMotionLevel);
See also
Camera.activityLevel, Camera.onActivity, Camera.onStatus,
Camera.setMotionLevel()
Camera.motionTimeOut
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public motionTimeOut : Number [read-only]
Description
Property (read-only); the number of milliseconds between the time the camera stops detecting motion and the time (2 seconds).
To set this value, use
Camera.onActivity(false) is invoked. The default value is 2000
Camera.setMotionLevel().
22 Client-Side ActionScript Language Reference
Example
In the following example, the ProgressBar instance changes its halo theme color when the activity level falls below the motion level. You can set the number of seconds for the
motionTimeout property using a NumericStepper instance. Create a new video instance by
selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name instance name
motionTimeOut_nstep, and a ProgressBar with the instance name motion_pb. Then add the
my_video. Add a Label component instance to the Stage and give it the
motionLevel_lbl, a NumericStepper with the instance name
following ActionScript to Frame 1 of the Timeline:
var motionLevel_lbl:mx.controls.Label; var motion_pb:mx.controls.ProgressBar; var motionTimeOut_nstep:mx.controls.NumericStepper; var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
this.onEnterFrame = function() { motionLevel_lbl.text = "activityLevel: "+my_cam.activityLevel; };
motion_pb.indeterminate = true; my_cam.onActivity = function(isActive:Boolean) { if (isActive) { motion_pb.setStyle("themeColor", "haloGreen"); motion_pb.label = "Motion is above "+my_cam.motionLevel; } else { motion_pb.setStyle("themeColor", "haloOrange"); motion_pb.label = "Motion is below "+my_cam.motionLevel; } }; function changeMotionTimeOut() { my_cam.setMotionLevel(my_cam.motionLevel, motionTimeOut_nstep.value/
1000); } motionTimeOut_nstep.addEventListener("change", changeMotionTimeOut); motionTimeOut_nstep.value = my_cam.motionTimeOut/1000;
See also
Camera.onActivity, Camera.setMotionLevel()
Camera class 23
Camera.muted
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public muted : Boolean [read-only]
Description
Property (read-only); a Boolean value that specifies whether the user has denied access to the camera ( value changes,
Example
In the following example, an error message could be displayed if my_cam.muted evaluates to
true. Create a new video instance by selecting New Video from the Library options menu.
Add an instance to the Stage and give it the instance name ActionScript to Frame 1 of the Timeline:
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); my_cam.onStatus = function(infoObj:Object) { if (my_cam.muted) {
trace("User denied access to Camera"); System.showSettings(0); } };
true) or allowed access (false) in the Flash Player Privacy dialog box. When this
Camera.onStatus is invoked. For more information, see Camera.get().
my_video. Then add the following
/* If user is denied access to their Camera, you can display an error message here. You can display the user's Camera/Privacy settings again using System.showSettings(0).*/
See also
Camera.get(), Camera.onStatus
24 Client-Side ActionScript Language Reference
Camera.name
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public name : String [read-only]
Description
Property (read-only); a string that specifies the name of the current camera, as returned by the camera hardware.
Example
The following example displays the name of the default camera in a text field and writes the name to the log file. In Windows, this name is the same as the device name listed in the Camera Settings panel.
Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name ActionScript to Frame 1 of the Timeline:
my_video. Then add the following
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
this.createTextField("name_txt", this.getNextHighestDepth(), 0, 0, 100,
22); name_txt.autoSize = true; name_txt.text = my_cam.name;
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Camera.get(), Camera.names
MovieClip.getNextHighestDepth() method.
Camera class 25
Camera.names
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public static names : Array [read-only]
NOTE
The correct syntax is Camera.names. To assign the return value to a variable, use syntax like
var cam_array:Array = Camera.names. To determine the name of the current camera,
active_cam.name, where active_cam is the variable to which you assigned the results
use of
Camera.get().
Description
Class property (read-only); retrieves an array of strings reflecting the names of all available video capture devices (including video capture cards and cameras) without displaying the Flash Player Privacy dialog box. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each camera driver and the number of camera drivers on the system (by means of Array class entry in the ActionScript 2.0 Language Reference.
Camera.names.length). For more information, see the
Calling the
Camera.names property requires an extensive examination of the hardware, and it
may take several seconds to build the array. In most cases, you can just use the default camera.
Example
The following example uses the default camera unless more than one camera is available, in which case the user can choose which camera to set as the default camera. If only one camera is present, the default camera is used.
Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name
my_video. Then add the following
ActionScript to Frame 1 of the Timeline:
var my_video:Video; var cam_array:Array = Camera.names; if (cam_array.length>1) { System.showSettings(3); } var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam);
See also
Camera.get(), Camera.index, Camera.names
26 Client-Side ActionScript Language Reference
Camera.onActivity
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public onActivity = function(activity:Boolean) {}
Parameters
activity A Boolean value set to true when the camera starts detecting motion, false
when it stops.
Returns
Nothing.
Description
Event handler; invoked when the camera starts or stops detecting motion. If you want to respond to this event handler, you must create a function to process its
activity value.
To specify the amount of motion required to invoke
Camera.onActivity(true) and the
amount of time that must elapse without activity before invoking
Camera.onActivity(false), use Camera.setMotionLevel().
Example
The following example displays true or false in the Output panel when the camera starts or stops detecting motion:
// assumes a Video object named "my_video" is on the Stage var active_cam:Camera = Camera.get(); my_video.attachVideo(active_cam); active_cam.setMotionLevel(10, 500); active_cam.onActivity = function(mode) {
trace(mode);
}
See also
Camera.setMotionLevel()
Camera class 27
Camera.onStatus
Availability
Flash Player 6.
Flash Media Server.
Usage
public onStatus = function(infoObject:Object) {}
Parameters
infoObject A parameter defined according to the status message. For more information
about this parameter, see “Camera information objects” on page 151.
Returns
Nothing.
Description
Event handler; invoked when one of the following events occurs:
The user allows access to the camera. The Camera.muted property is set to false, and
this handler is invoked with an information object whose
Camera.Unmuted.
code property is
The user denies access to the camera. The Camera.muted property is set to true, and this
handler is invoked with an information object whose
code property is Camera.Muted.
When a SWF file tries to access the camera, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access. To determine whether the user has denied or allowed access to the camera without processing this event handler, use the
Camera.muted
property.
NOTE
If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this handler is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see
Camera.get().
If you want to respond to this event handler, you must create a function to process the information object generated by the camera. For more information, see Appendix A, “Client-
Side Information Objects,” on page 149.
28 Client-Side ActionScript Language Reference
Example
The following event handler displays a message whenever the user allows or denies access to the camera:
// assumes a Video object named "my_video" is on the Stage var active_cam:Camera = Camera.get(); my_video.attachVideo(active_cam); active_cam.onStatus = function(infoMsg) {
if(infoMsg.code == "Camera.Muted"){
trace("User denies access to the camera"); } else
trace("User allows access to the camera");
} // Change the Allow or Deny value to invoke the function. System.showSettings(0);
See also
Camera.get(), Camera.muted, System.showSettings()
Camera.quality
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public quality : Number [read-only]
Description
Property (read-only); an integer specifying the required level of picture quality, as determined by the amount of compression being applied to each video frame. Acceptable quality values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). The default value is 0, which means that picture quality can vary as needed to avoid exceeding available bandwidth.
Camera class 29
Example
The following example uses a NumericStepper instance to specify the amount of compression applied to the camera feed. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name Add a NumericStepper with the instance name
quality_nstep. Then add the following
my_video.
ActionScript to Frame 1 of the Timeline:
var quality_nstep:mx.controls.NumericStepper;
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
quality_nstep.minimum = 0; quality_nstep.maximum = 100; quality_nstep.stepSize = 5; quality_nstep.value = my_cam.quality;
function changeQuality() { my_cam.setQuality(my_cam.bandwidth, quality_nstep.value); } quality_nstep.addEventListener("change", changeQuality);
See also
Camera.setQuality()
Camera.setKeyFrameInterval()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setKeyFrameInterval(keyframeInterval : Number) : Void
Parameters
keyframeInterval A numeric value that specifies which video frames are transmitted in
full (called keyframes) instead of being interpolated by the video compression algorithm. A value of 1 means that every frame is a keyframe, a value of 3 means that every third frame is a keyframe, and so on. Acceptable values are 1 through 48. The default value is 15.
Returns
Nothing.
30 Client-Side ActionScript Language Reference
Description
Method; specifies which video frames are transmitted in full (called keyframes) instead of being interpolated by the video compression algorithm. This method is generally applicable only if you are transmitting video using Flash Media Server.
The Flash Video compression algorithm compresses video by transmitting only what has changed since the last frame of the video; these portions are considered to be interpolated frames. It may help to compare this concept with how tweening and keyframes interact within the Flash authoring environment: the frames between keyframes are created (interpolated) based on the contents of the previous frame. Similarly, frames of a video can be interpolated according to the contents of the previous frame. A keyframe, however, is a video frame that is complete; it is not interpolated from prior frames.
To determine how to set a value for video playback accessibility. For example, specifying a higher value for
keyframeInterval, consider both bandwidth use and
keyframeInterval
(sending keyframes less frequently) reduces bandwidth use. However, this may increase the amount of time required to position the playhead at a particular point in the video; more prior video frames may have to be interpolated before the video can resume.
Conversely, specifying a lower value for
keyframeInterval (sending keyframes more
frequently) increases bandwidth use because entire video frames are transmitted more often, but may decrease the amount of time required to seek a particular video frame within a recorded video.
See also
Camera.keyFrameInterval
Camera.setLoopback()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setLoopback(compressLocalStream : Boolean) : Void
Parameters
compressLocalStream A Boolean value that specifies whether to use a compressed video
stream (
true) or an uncompressed stream (false) for a local view of what the camera is
receiving. The default value is
false.
Camera class 31
Returns
Nothing.
Description
Method; specifies whether to use a compressed video stream for a local view of the camera. This method is generally applicable only if you are transmitting video using the Flash Media Server; setting
compressLocalStream to true lets you see more precisely how the video will
appear to users when they view it in real time.
Although a compressed stream is useful for testing purposes, such as previewing video quality settings, it has a significant processing cost, because the local view is not simply compressed; it is compressed, edited for transmission as it would be over a live connection, and then decompressed for local viewing.
To set the amount of compression used when you set
Camera.setQuality().
compressLocalStream to true, use
Example
In the following example, if the user presses a loopback button, the loopback value is set to
true:
on (press) {
if (_root.active_cam.loopback==false) {
_root.active_cam.setLoopback(true); } else {
debugWindow+="You're already compressing the stream." + newline; }
See also
Camera.loopback, Camera.setQuality()
Camera.setMode()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setMode([width:Number], [height:Number], [fps:Number],
[favorArea:Boolean]) : Void
32 Client-Side ActionScript Language Reference
Parameters
width The requested capture width, in pixels. The default value is 160.
height The requested capture height, in pixels. The default value is 120.
fps The requested rate at which the camera should capture data, in frames per second. The
default value is 15.
favorArea An optional Boolean value that specifies how to manipulate the width, height,
and frame rate if the camera does not have a native mode that meets the specified requirements. The default value is favored; using this parameter selects the mode that most closely matches
true, which means that maintaining capture size is
width and height
values, even if doing so adversely affects performance by reducing the frame rate. To maximize frame rate at the expense of camera height and width, pass
false for the favorArea
parameter.
Returns
Nothing.
Description
Method; sets the camera capture mode to the native mode that best meets the specified requirements. If the camera does not have a native mode that matches all the parameters you pass, Flash selects a capture mode that most closely synthesizes the requested mode. This manipulation may involve cropping the image and dropping frames.
By default, Flash drops frames as needed to maintain image size. To minimize the number of dropped frames, even if this means reducing the size of the image, pass
favorArea parameter.
false for the
When choosing a native mode, Flash tries to maintain the requested aspect ratio whenever possible. For example, if you issue the command
active_cam.setMode(400, 400, 30), and
the maximum width and height values available on the camera are 320 and 288, Flash sets both the width and height at 288. By setting these properties to the same value, Flash maintains the 1:1 aspect ratio you requested.
To determine the values assigned to these properties after Flash selects the mode that most closely matches your requested values, use
Camera.width, Camera.height, and Camera.fps.
If you are using Flash Media Server, you can also capture single frames or create time-lapsed photography. For more information, see
NetStream.attachVideo().
Camera class 33
Example
The following example sets the camera capture mode. You can type a frame rate into a TextInput instance and press Enter or Return to apply the frame rate.
Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name instance with the instance name
fps_ti. Then add the following ActionScript to Frame 1 of
my_video. Add a TextInput component
the Timeline:
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam);
fps_ti.maxChars = 2; fps_ti.restrict = [0-9]; fps_lbl.text = "Current: "+my_cam.fps+" fps";
function changeFps():Void { my_cam.setMode(my_cam.width, my_cam.height, fps_ti.text); fps_lbl.text = "Current: "+my_cam.fps+" fps"; fps_ti.text = my_cam.fps; Selection.setSelection(0,2); } fps_ti.addEventListener("enter", changeFps);
See also
Camera.currentFps, Camera.fps, Camera.height, Camera.width,
NetStream.attachVideo()
Camera.setMotionLevel()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setMotionLevel([motionLevel:Number], [timeOut:Number]) : Void
Parameters
motionLevel A numeric value that specifies the amount of motion required to invoke
Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.
timeout An optional numeric parameter that specifies how many milliseconds must elapse
without activity before Flash considers activity to have stopped and invokes the
Camera.onActivity(false) event handler. The default value is 2000 (2 seconds).
34 Client-Side ActionScript Language Reference
Returns
Nothing.
Description
Method; specifies how much motion is required to invoke Camera.onActivity(true). Optionally sets the number of milliseconds that must elapse without activity before Flash considers motion to have stopped and invokes
NOTE
Video can be displayed regardless of the value of the motionLevel parameter. This parameter only determines when and under what circumstances invoked—not whether video is actually being captured or displayed.
To prevent the camera from detecting motion at all, pass a value of 100 for motionLevel;
Camera.onActivity is never invoked. (You would probably use this value only for testing
Camera.onActivity(false).
Camera.onActivity is
purposes—for example, to temporarily disable any actions set to occur when
Camera.onActivity is invoked.)
To determine the amount of motion the camera is currently detecting, use the
Camera.activityLevel property.
Motion level values correspond directly to activity values. Complete lack of motion is an activity value of 0. Constant motion is an activity value of 100. Your activity value is less than your motion level value when you’re not moving; when you are moving, activity values frequently exceed your motion level value.
This method is similar in purpose to used to specify when the
onActivity event handler should be invoked. However, these
Microphone.setSilenceLevel(); both methods are
methods have a significantly different impact on publishing streams:
Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio
stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.
Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth
usage. Even if a video stream does not detect motion, video is still sent.
Camera class 35
Example
The following example sends messages to the Output panel when video activity starts or stops. Change the motion sensitivity value of 30 to a higher or lower number to see how different values affect motion detection.
// assumes a Video object named "myVideoObject" is on the Stage active_cam = Camera.get(); x = 0; function motion(mode) { trace(x + ": " + mode); x++; } active_cam.onActivity = function(mode) { motion(mode); } active_cam.setMotionLevel(30, 500); myVideoObject.attachVideo(active_cam);
See also
Camera.activityLevel, Camera.motionLevel, Camera.motionTimeOut,
Camera.onActivity
Camera.setQuality()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setQuality([bandwidth:Number], [quality:Number]) : Void
Parameters
bandwidth An integer that specifies the maximum amount of bandwidth that the current
outgoing video feed can use, in bytes per second. To specify that Flash Video can use as much bandwidth as needed to maintain the value of value is 16384.
quality, pass 0 for bandwidth. The default
36 Client-Side ActionScript Language Reference
quality An integer that specifies the required level of picture quality, as determined by the
amount of compression being applied to each video frame. Acceptable values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). To specify that picture quality can vary as needed to avoid exceeding bandwidth, pass 0 for
quality. The
default value is 0.
TIP
Streams compressed with the lossless codec are larger than streams compressed with the default Sorenson codec.
Returns
Nothing.
Description
Method; sets the maximum amount of bandwidth per second or the required picture quality of the current outgoing video feed.
Use this method to specify which element of the outgoing video feed is more important to your application—bandwidth use or picture quality.
To indicate that bandwidth use takes precedence, pass a value for bandwidth and 0 for
quality. Flash will transmit video at the highest quality possible within the specified
bandwidth. If necessary, Flash will reduce picture quality to avoid exceeding the specified bandwidth. In general, as motion increases, quality decreases.
To indicate that quality takes precedence, pass 0 for bandwidth and a numeric value for
quality. Flash will use as much bandwidth as required to maintain the specified quality.
If necessary, Flash will reduce the frame rate to maintain picture quality. In general, as motion increases, bandwidth use also increases.
To specify that both bandwidth and quality are equally important, pass numeric values for
both parameters. Flash will transmit video that achieves the specified quality and that doesn’t exceed the specified bandwidth. If necessary, Flash will reduce the frame rate to maintain picture quality without exceeding the specified bandwidth.
Example
The following examples illustrate how to use this method to control bandwidth use and picture quality:
// Ensure that no more than 8192 (8K/second) is used to send video. active_cam.setQuality(8192,0);
/* Ensure that no more than 8192 (8K/second) is used to send video with a minimum quality of 50.*/ active_cam.setQuality(8192,50);
// Ensure a minimum quality of 50, no matter how much bandwidth it takes. active_cam.setQuality(0,50);
Camera class 37
See also
Camera.bandwidth, Camera.get(), Camera.quality
Camera.width
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public width : Number [read-only]
Description
Property (read-only); the current capture width, in pixels. To set a desired value for this property, use
Example
The following code displays the current width, height and FPS of a video instance in a Label component instance on the Stage. Create a new video instance by selecting New Video from the Library options menu. Add an instance to the Stage and give it the instance name
my_video. Add a Label component instance to the Stage and give it the instance name dimensions_lbl. Then add the following ActionScript to Frame 1 of the Timeline:
Camera.setMode().
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); var dimensions_lbl:mx.controls.Label; dimensions_lbl.setStyle("fontSize", 9); dimensions_lbl.setStyle("fontWeight", "bold"); dimensions_lbl.setStyle("textAlign", "center"); dimensions_lbl.text = "width: "+my_cam.width+", height: "+my_cam.height+",
FPS: "+my_cam.fps;
See also
Camera.height, Camera.setMode()
Microphone class
Availability
Flash Player 6.
Flash Media Server (not required).
38 Client-Side ActionScript Language Reference
The Microphone class lets you capture audio from a microphone attached to the computer that is running Flash Player.
When used with Flash Media Server, this class lets you transmit, play, and optionally record the audio being captured. With these capabilities, you can develop media applications such as instant messaging with audio, recording presentations so others can replay them at a later date, and so on. Flash provides similar video capabilities; for more information, see the
Camera class entry.
You can also use a Microphone object without a server—for example, to transmit sound from your microphone through the speakers on your local system.
To create or reference a Microphone object, use the
NOTE
Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.
Microphone.get() method.
Method summary for the Microphone class
Method Description
Microphone.get() Returns a default or specified Microphone object,
or
null if the microphone is not available.
Microphone.setGain() Specifies the amount by which the microphone
should boost the signal.
Microphone.setRate() Specifies the rate at which the microphone should
capture sound, in kHz.
Microphone.setSilenceLevel() Specifies the amount of sound required to activate
the microphone.
Microphone.setUseEchoSuppression() Specifies whether to use the echo suppression
feature of the audio codec.
Property summary for the Microphone class
Property (read-only) Description
Microphone.activityLevel The amount of sound the microphone is detecting.
Microphone.gain The amount by which the microphone boosts the signal
Microphone.index The index of the current microphone.
before transmitting it.
Microphone class 39
Property (read-only) Description
Microphone.muted A Boolean value that specifies whether the user has
allowed or denied access to the microphone.
Microphone.name The name of the current sound capture device, as
returned by the sound capture hardware.
Microphone.names Class property: an array of strings reflecting the names
of all available sound capture devices, including sound capture cards and microphones.
Microphone.rate The sound capture rate, in kHz.
Microphone.silenceLevel The amount of sound required to activate the
microphone.
Microphone.silenceTimeout The number of milliseconds between the time the
microphone stops detecting sound and the time
Microphone.onActivity(false) is called.
Microphone.useEchoSuppression A Boolean value that specifies whether echo
suppression is being used.
Event handler summary for the Microphone class
Method Description
Microphone.onActivity Invoked when the microphone starts or stops detecting
sound.
Microphone.onStatus Invoked when the user allows or denies access to the
microphone.
Constructor for the Microphone class
See Microphone.get().
Microphone.activityLevel
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public activityLevel : Number [read-only]
40 Client-Side ActionScript Language Reference
Description
Property (read-only); a numeric value that specifies the amount of sound the microphone is detecting. Values range from 0 (no sound is being detected) to 100 (very loud sound is being detected). The value of this property can help you determine a good value to pass to the
Microphone.setSilenceLevel() method.
If the microphone is available but is not yet being used because neither
MovieClip.attachAudio() nor NetStream.attachAudio() has been called, this property
is set to -1.
Example
The following example displays the activity level of the current microphone in a ProgressBar instance called
var activityLevel_pb:mx.controls.ProgressBar; activityLevel_pb.mode = "manual"; activityLevel_pb.label = "Activity Level: %3%%"; activityLevel_pb.setStyle("themeColor", "0xFF0000"); this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); this.onEnterFrame = function() { activityLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.onActivity = function(active:Boolean) { if (active) { var haloTheme_str:String = "haloGreen"; } else { var haloTheme_str:String = "0xFF0000"; } activityLevel_pb.setStyle("themeColor", haloTheme_str); };
activityLevel_pb:
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.setGain()
MovieClip.getNextHighestDepth() method.
Microphone class 41
Microphone.gain
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public gain : Number [read-only]
Description
Property (read-only); the amount by which the microphone boosts the signal. Valid values are 0 to 100. The default value is 50.
Example
The following example uses a ProgressBar instance called gain_pb to display and a NumericStepper instance called
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
gain_pb.label = "Gain: %3"; gain_pb.mode = "manual"; gain_pb.setProgress(active_mic.gain, 100); gain_nstep.value = active_mic.gain;
gain_nstep to set the microphone's gain value:
function changeGain() { active_mic.setGain(gain_nstep.value); gain_pb.setProgress(active_mic.gain, 100); } gain_nstep.addEventListener("change", changeGain);
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.setGain()
42 Client-Side ActionScript Language Reference
MovieClip.getNextHighestDepth() method.
Microphone.get()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public static get([index:Number]) : Microphone
NOTE
The correct syntax is Microphone.get(). To assign the Microphone object to a variable, use syntax like
Parameters
index An optional zero-based integer that specifies which microphone to get, as determined
from the array returned by recommended for most applications), omit this parameter.
Returns
If index is not specified, this method returns a reference to the default microphone, or if
it is not available, to the first available microphone. If no microphones are available or installed, the method returns
var active_mic:Microphone = Microphone.get().
Microphone.names. To get the default microphone (which is
null.
If index is specified, this method returns a reference to the requested microphone, or
null if it is not available.
Description
Method; returns a reference to a Microphone object for capturing audio. To actually begin capturing the audio, you must attach the Microphone object either to a MovieClip object (see
MovieClip.attachAudio()) or to a NetStream object (see NetStream.attachAudio()).
(The NetStream object is available only with Flash Media Server.)
Unlike objects that you create using the
new constructor, multiple calls to Microphone.get()
reference the same microphone. Thus, if your script contains the lines
mic1 = Microphone.get() and mic2 = Microphone.get(), both mic1 and mic2 reference
the same (default) microphone.
In general, you shouldn’t pass a value for
index; simply use the Microphone.get() method
to return a reference to the default microphone. By means of the Microphone Settings panel (discussed later in this section), the user can specify the default microphone Flash should use. If you pass a value for one the user prefers. You might use
index, you might be trying to reference a microphone other than the
index in rare cases—for example, if your application is
capturing audio from two microphones at the same time.
Microphone class 43
When a SWF file tries to access the microphone returned by the Microphone.get() method—for example, when you issue NetStream.attachAudio() or
MovieClip.attachAudio()—Flash Player displays a Privacy dialog box that lets the user
choose whether to allow or deny access to the microphone. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.)
When the user responds to this dialog box, the
Microphone.onStatus event handler returns
an information object that indicates the user’s response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use
Microphone.muted.
The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing and selecting Settings. When the Privacy dialog box opens, the user selects Remember.
You can’t use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy dialog box for the user by using
System.showSettings(0). If the user selects
Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.
If
Microphone.get() returns null, either the microphone is in use by another application,
or there are no microphones installed on the system. To determine whether any microphones are installed, use
Microphones.names.length. To display the Flash Player Microphone
Settings panel, which lets the user choose the microphone to be referenced by
Microphone.get(), use System.showSettings(2).
Example
The following example lets the user specify the default microphone, and then captures audio and plays it back locally. To avoid feedback, you may want to test this code while wearing headphones.
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); System.showSettings(2); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.index, Microphone.muted, Microphone.names, Microphone.onStatus, MovieClip.attachAudio(), NetStream.attachAudio(), System.showSettings()
44 Client-Side ActionScript Language Reference
MovieClip.getNextHighestDepth() method.
Microphone.index
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public index : Number [read-only]
Description
Property (read-only); a zero-based integer that specifies the index of the microphone, as reflected in the array returned by
Example
The following example displays the names of the sound capturing devices available on your computer system in a ComboBox instance called component, called
mic_lbl, displays the index microphone. You can use the ComboBox to
switch between the devices.
var mic_lbl:mx.controls.Label; var mic_cb:mx.controls.ComboBox;
Microphone.names.
mic_cb. An instance of the Label
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); mic_lbl.text = "["+active_mic.index+"] "+active_mic.name; mic_cb.dataProvider = Microphone.names; mic_cb.selectedIndex = active_mic.index;
var cbListener:Object = new Object(); cbListener.change = function(evt:Object) { active_mic = Microphone.get(evt.target.selectedIndex); sound_mc.attachAudio(active_mic); mic_lbl.text = "["+active_mic.index+"] "+active_mic.name; }; mic_cb.addEventListener("change", cbListener);
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.get(), Microphone.names
MovieClip.getNextHighestDepth() method.
Microphone class 45
Microphone.muted
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public muted : Boolean [read-only]
Description
Property (read-only); a Boolean value that specifies whether the user has denied access to the microphone (
Microphone.onStatus is invoked. For more information, see Microphone.get().
Example
This example gets the default microphone and checks whether it is muted:
var active_mic:Microphone = Microphone.get(); trace(active_mic.muted);
See also
true) or allowed access (false). When this value changes,
Microphone.get(), Microphone.onStatus
Microphone.name
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public name : String [read-only]
Description
Property (read-only); a string that specifies the name of the current sound capture device, as returned by the sound capture hardware.
46 Client-Side ActionScript Language Reference
Example
The following example displays information about the sound capture device(s) on your computer system, including an array of names and the default device:
var status_ta:mx.controls.TextArea; status_ta.html = false; status_ta.setStyle("fontSize", 9); var microphone_array:Array = Microphone.names; var active_mic:Microphone = Microphone.get(); status_ta.text = "The default device is: "+active_mic.name+newline+newline; status_ta.text += "You have "+microphone_array.length+" device(s)
installed."+newline+newline;
for (var i = 0; i<microphone_array.length; i++) { status_ta.text += "["+i+"] "+microphone_array[i]+newline; }
See also
Microphone.get(), Microphone.names
Microphone.names
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public static names : Array {read-only]
NOTE
The correct syntax is Microphone.names. To assign the return value to a variable, use syntax like the current microphone, use you assigned the results of
var micNames_array:Array = Microphone.names. To determine the name of
active_mic.name, where active_mic is the variable to which
Microphone.get().
Description
Class property (read-only); retrieves an array of strings reflecting the names of all available sound capture devices without displaying the Flash Player Privacy dialog box. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each sound capture device and the number of sound capture devices on the system (by means of
Microphone.names.length). For more information, see the Array class entry in
ActionScript 2.0 Language Reference.
Calling
Microphone.names requires an extensive examination of the hardware, and it may
take several seconds to build the array. In most cases, you can just use the default microphone.
Microphone class 47
Example
The following code returns information on the array of audio devices:
var allMicNames_array:Array = Microphone.names; trace("Microphone.names located these device(s):"); for(i=0; i < allMicNames_array.length; i++){ trace("[" + i + "]: " + allMicNames_array[i]); }
For example, the following information could be displayed:
Microphone.names located these device(s): [0]: Crystal SoundFusion(tm) [1]: USB Audio Device
See also
Array class entry in the ActionScript 2.0 Language Reference, Microphone.get(),
Microphone.name
Microphone.onActivity
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public onActivity = function(active:Boolean) {}
Parameters
active A Boolean value set to true when the microphone starts detecting sound, false
when it stops.
Returns
Nothing.
Description
Event handler; invoked when the microphone starts or stops detecting sound. If you want to respond to this event handler, you must create a function to process its
To specify the amount of sound required to invoke amount of time that must elapse without sound before invoked, use
Microphone.setSilenceLevel().
Microphone.onActivity(true), and the
Microphone.onActivity(false) is
active value.
48 Client-Side ActionScript Language Reference
Example
The following example displays true or false in the Output panel when the microphone starts or stops detecting sound.
var active_mic:Microphone = Microphone.get(); _root.attachAudio(active_mic); active_mic.onActivity = function(mode){
trace(mode);
}
See also
Microphone.setSilenceLevel()
Microphone.onStatus
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public onStatus = function(infoObject:Object) {}
Parameters
infoObject A parameter defined according to the status message. For more information
about this parameter, see “Microphone information objects” on page 151.
Returns
Nothing.
Description
Event handler; invoked when the user allows or denies access to the microphone. If you want to respond to this event handler, you must create a function to process the information object generated by the microphone. For more information, see Appendix A, “Client-Side
Information Objects,” on page 149.
Microphone class 49
When a SWF file tries to access the microphone, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access.
If the user allows access, the Microphone.muted property is set to false, and this event
handler is invoked with an information object whose
Microphone.Unmuted.
If the user denies access, the Microphone.muted property is set to true, and this event
handler is invoked with an information object whose
Microphone.Muted.
code property is
code property is
To determine whether the user has denied or allowed access to the microphone without processing this event handler, use
NOTE
If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this method is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see
Example
Microphone.muted.
Microphone.get().
The following example launches the Privacy dialog box, where the user can allow or deny access to the microphone. If the user chooses to deny access, “muted” is displayed in large red text. If microphone access is allowed, the user does not see this text.
this.createTextField("muted_txt", this.getNextHighestDepth(), 10, 10, 100,
22);
muted_txt.autoSize = true; muted_txt.html = true; muted_txt.selectable = false; muted_txt.htmlText = "<a href=\"asfunction:System.showSettings\"><u>Click
Here</u></a> to Allow/Deny access.";
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); active_mic.onStatus = function(infoObj:Object) { status_txt._visible = active_mic.muted; muted_txt.htmlText = "Status: <a
href=\"asfunction:System.showSettings\"><u>"+infoObj.code+"</u></a>";
}; this.createTextField("status_txt", this.getNextHighestDepth(), 0, 0, 100,
22);
status_txt.html = true; status_txt.autoSize = true; status_txt.htmlText = "<font size='72' color='#FF0000'>muted</font>"; status_txt._x = (Stage.width-status_txt._width)/2; status_txt._y = (Stage.height-status_txt._height)/2; status_txt._visible = active_mic.muted;
50 Client-Side ActionScript Language Reference
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.get(), Microphone.muted, System.showSettings()
MovieClip.getNextHighestDepth() method.
Microphone.rate
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public rate : Number [read-only]
Description
Property (read-only); the rate at which the microphone is capturing sound, in kHz. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.
To set this value, use
Microphone.setRate().
Example
The following example saves the current rate to the variable original:
var active_mic:Microphone = Microphone.get(); var original:Number = active_mic.rate;
See also
Microphone.setRate()
Microphone.setGain()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setGain(gain : Number) : Void
Microphone class 51
Parameters
gain An integer that specifies the amount by which the microphone should boost the
signal. Valid values are 0 to 100. The default value is 50; however, the user may change this value in the Flash Player Microphone Settings panel.
Returns
Nothing.
Description
Method; sets the microphone gain—that is, the amount by which the microphone should multiply the signal before transmitting it. A value of 0 tells Flash to multiply by 0; that is, the microphone transmits no sound.
You can think of this setting like a volume knob on a stereo: 0 is no volume and 50 is normal volume. Numbers below 50 specify lower than normal volume, while numbers above 50 specify higher than normal volume.
Example
The following example ensures that the microphone gain setting is less than or equal to 55.
var active_mic:Microphone = Microphone.get(); if (active_mic.gain > 55){
active_mic.setGain(55);
}
See also
Microphone.gain, Microphone.setUseEchoSuppression()
Microphone.setRate()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setRate(kHz : Number) : Void
Parameters
kHz The rate at which the microphone should capture sound, in kHz. Acceptable values
are 5, 8, 11, 22, and 44. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.
52 Client-Side ActionScript Language Reference
Returns
Nothing.
Description
Method; sets the rate, in kHz, at which the microphone should capture sound.
Example
The following example sets the microphone rate to the user’s preference (which you have assigned to the
userRate variable) if it is one of the following values: 5, 8, 11, 22, or 44. If it
is not, the value is rounded to the nearest acceptable value that the sound capture device supports.
active_mic.setRate(userRate);
See also
Microphone.rate
Microphone.setSilenceLevel()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setSilenceLevel(silenceLevel:Number, [timeOut:Number]) : Void
Parameters
silenceLevel An integer that specifies the amount of sound required to activate the
microphone and invoke
Microphone.onActivity(true). Acceptable values range from 0
to 100. The default value is 10.
timeOut An optional integer parameter that specifies how many milliseconds must elapse
without activity before Flash considers sound to have stopped and invokes
Microphone.onActivity(false). The default value is 2000 (2 seconds).
Returns
Nothing.
Microphone class 53
Description
Method; sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun.
To prevent the microphone from detecting sound at all, pass a value of 100 for
silenceLevel; Microphone.onActivity is never invoked.
To determine the amount of sound the microphone is currently detecting, use
Microphone.activityLevel.
Activity detection is the ability to detect when audio levels suggest that a person is talking. When someone is not talking, bandwidth can be saved because there is no need to send the associated audio stream. This information can also be used for visual feedback so that users know they (or others) are silent.
Silence values correspond directly to activity values. Complete silence is an activity value of 0. Constant loud noise (as loud as can be registered based on the current gain setting) is an activity value of 100. After gain is appropriately adjusted, your activity value is less than your silence value when you’re not talking; when you are talking, the activity value exceeds your silence value.
This method is similar in purpose to specify when the
onActivity event handler should be invoked. However, these methods have
Camera.setMotionLevel(); both methods are used to
a significantly different impact on publishing streams:
Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth
usage. Even if a video stream does not detect motion, video is still sent.
Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio
stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.
Example
The following example changes the silence level based on the user’s input in a NumericStepper instance called
silenceLevel_pb modifies its appearance depending on whether the audio stream is
silenceLevel_nstep. The ProgressBar instance called
considered silent. If the audio stream is not silent, the progress bar displays the activity level of the audio stream.
54 Client-Side ActionScript Language Reference
var silenceLevel_pb:mx.controls.ProgressBar; var silenceLevel_nstep:mx.controls.NumericStepper;
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
silenceLevel_pb.label = "Activity level: %3"; silenceLevel_pb.mode = "manual"; silenceLevel_nstep.minimum = 0; silenceLevel_nstep.maximum = 100; silenceLevel_nstep.value = active_mic.silenceLevel;
var nstepListener:Object = new Object(); nstepListener.change = function(evt:Object) { active_mic.setSilenceLevel(evt.target.value,
active_mic.silenceTimeOut);
}; silenceLevel_nstep.addEventListener("change", nstepListener);
this.onEnterFrame = function() { silenceLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.onActivity = function(active:Boolean) { if (active) { silenceLevel_pb.indeterminate = false; silenceLevel_pb.setStyle("themeColor", "haloGreen"); silenceLevel_pb.label = "Activity level: %3"; } else { silenceLevel_pb.indeterminate = true; silenceLevel_pb.setStyle("themeColor", "0xFF0000"); silenceLevel_pb.label = "Activity level: (inactive)"; } };
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also the example for
See also
Microphone.activityLevel, Microphone.onActivity, Microphone.setGain(), Microphone.silenceLevel, Microphone.silenceTimeout
MovieClip.getNextHighestDepth() method.
Camera.setMotionLevel().
Microphone class 55
Microphone.setUseEchoSuppression()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public setUseEchoSuppression(suppress : Boolean) : Void
Parameters
suppress A Boolean value indicating whether echo suppression should be used (true) or
not (
false).
Returns
Nothing.
Description
Method; specifies whether to use the echo suppression feature of the audio codec. The default value is Settings panel.
false unless the user has selected Reduce Echo in the Flash Player Microphone
Echo suppression is an effort to reduce the effects of audio feedback, which is caused when sound going out the speaker is picked up by the microphone on the same computer. (This is different from echo cancellation, which completely removes the feedback.)
Generally, echo suppression is advisable when the sound being captured is played through speakers—instead of a headset—on the same computer. If your SWF file allows users to specify the sound output device, you may want to call
Microphone.setUseEchoSuppression(true) if they indicate they are using speakers and
will be using the microphone as well.
Users can also adjust these settings in the Flash Player Microphone Settings panel.
56 Client-Side ActionScript Language Reference
Example
The following example turns on echo suppression if the user selects a CheckBox instance called
useEchoSuppression_ch. The ProgressBar instance called activityLevel_pb
displays the current activity level of the audio stream.
var useEchoSuppression_ch:mx.controls.CheckBox; var activityLevel_pb:mx.controls.ProgressBar;
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
activityLevel_pb.mode = "manual"; activityLevel_pb.label = "Activity Level: %3"; useEchoSuppression_ch.selected = active_mic.useEchoSuppression; this.onEnterFrame = function() { activityLevel_pb.setProgress(active_mic.activityLevel, 100); }; var chListener:Object = new Object(); chListener.click = function(evt:Object) { active_mic.setUseEchoSuppression(evt.target.selected); }; useEchoSuppression_ch.addEventListener("click", chListener);
See also
Microphone.setGain(), Microphone.useEchoSuppression
Microphone.silenceLevel
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public silenceLevel : Number [read-only]
Description
Property (read-only); an integer that specifies the amount of sound required to activate the microphone and invoke
Microphone.onActivity(true). The default value is 10.
Microphone class 57
Example
The following example changes the silence level based on the user's input in a NumericStepper instance called
silenceLevel_pb modifies its appearance depending on whether the audio stream is
silenceLevel_nstep. The ProgressBar instance called
considered silent. If the audio stream is not silent, the progress bar displays the activity level of the audio stream.
var silenceLevel_pb:mx.controls.ProgressBar; var silenceLevel_nstep:mx.controls.NumericStepper;
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
silenceLevel_pb.label = "Activity level: %3"; silenceLevel_pb.mode = "manual"; silenceLevel_nstep.minimum = 0; silenceLevel_nstep.maximum = 100; silenceLevel_nstep.value = active_mic.silenceLevel;
var nstepListener:Object = new Object(); nstepListener.change = function(evt:Object) { active_mic.setSilenceLevel(evt.target.value,
active_mic.silenceTimeOut);
}; silenceLevel_nstep.addEventListener("change", nstepListener);
this.onEnterFrame = function() { silenceLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.onActivity = function(active:Boolean) { if (active) { silenceLevel_pb.indeterminate = false; silenceLevel_pb.setStyle("themeColor", "haloGreen"); silenceLevel_pb.label = "Activity level: %3"; } else { silenceLevel_pb.indeterminate = true; silenceLevel_pb.setStyle("themeColor", "0xFF0000"); silenceLevel_pb.label = "Activity level: (inactive)"; } };
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
MovieClip.getNextHighestDepth() method.
58 Client-Side ActionScript Language Reference
See also
Microphone.gain, Microphone.onActivity, Microphone.setSilenceLevel()
Microphone.silenceTimeout
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public silenceTimeout : Number [read-only]
Description
Property (read-only); a numeric value representing the number of milliseconds between the time the microphone stops detecting sound and the time is invoked. The default value is 2000 (2 seconds).
Microphone.onActivity(false)
To set this value, use
Microphone.setSilenceLevel().
Example
The following example enables the user to control the amount of time between when the microphone stops detecting sound and when The user controls this value using a NumericStepper instance called The ProgressBar instance called
silenceLevel_pb modifies its appearance depending on
Microphone.onActivity(false) is invoked.
silenceTimeOut_nstep.
whether the audio stream is considered silent. If the audio stream is not silent, the progress bar displays the activity level of the audio stream.
var silenceLevel_pb:mx.controls.ProgressBar; var silenceTimeOut_nstep:mx.controls.NumericStepper;
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
silenceLevel_pb.label = "Activity level: %3"; silenceLevel_pb.mode = "manual"; silenceTimeOut_nstep.minimum = 0; silenceTimeOut_nstep.maximum = 10; silenceTimeOut_nstep.value = active_mic.silenceTimeOut/1000;
var nstepListener:Object = new Object(); nstepListener.change = function(evt:Object) { active_mic.setSilenceLevel(active_mic.silenceLevel, evt.target.value
1000);
};
Microphone class 59
silenceTimeOut_nstep.addEventListener("change", nstepListener);
this.onEnterFrame = function() { silenceLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.onActivity = function(active:Boolean) { if (active) { silenceLevel_pb.indeterminate = false; silenceLevel_pb.setStyle("themeColor", "haloGreen"); silenceLevel_pb.label = "Activity level: %3"; } else { silenceLevel_pb.indeterminate = true; silenceLevel_pb.setStyle("themeColor", "0xFF0000"); silenceLevel_pb.label = "Activity level: (inactive)"; } };
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
MovieClip.getNextHighestDepth() method.
Microphone.onActivity, Microphone.setSilenceLevel()
Microphone.useEchoSuppression
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public useEchoSuppression : Boolean [read-only]
Description
Property (read-only); a Boolean value of true if echo suppression is enabled; otherwise,
false. The default value is false unless the user has selected Reduce Echo in the Flash Player
Microphone Settings panel.
60 Client-Side ActionScript Language Reference
Example
The following example turns on echo suppression if the user selects a CheckBox instance called
useEchoSuppression_ch. The ProgressBar instance called activityLevel_pb
displays the current activity level of the audio stream.
var useEchoSuppression_ch:mx.controls.CheckBox; var activityLevel_pb:mx.controls.ProgressBar;
this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic);
activityLevel_pb.mode = "manual"; activityLevel_pb.label = "Activity Level: %3"; useEchoSuppression_ch.selected = active_mic.useEchoSuppression; this.onEnterFrame = function() { activityLevel_pb.setProgress(active_mic.activityLevel, 100); }; var chListener:Object = new Object(); chListener.click = function(evt:Object) { active_mic.setUseEchoSuppression(evt.target.selected); }; useEchoSuppression_ch.addEventListener("click", chListener);
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone.setUseEchoSuppression()
MovieClip.getNextHighestDepth() method.
MovieClip class
This class is discussed in detail in ActionScript 2.0 Language Reference. Only the method used by Flash Media Server is discussed in this section.
Method summary for the MovieClip class
Method Description
MovieClip.attachAudio() Starts or stops playback of an audio source.
MovieClip class 61
MovieClip.attachAudio()
Availability
Flash Player 6.
Flash Media Server (not required).
Usage
public attachAudio(source : Object) : Void
Parameters
source The object containing the audio to play. Valid values are a Microphone object, a
NetStream object (requires Flash Media Server), and
NOTE
In Flash Player 7 and later, source can also be a NetStream object playing an FLV file without the use of Flash Media Server. For more information, see the NetStream class entry in ActionScript 2.0 Language Reference.
Returns
Nothing.
Description
false (stops playing the audio).
Method; specifies the audio source to be either played locally (Microphone object) or streamed from the Flash Media Server (NetStream object). To stop playing the audio source, pass
false for source.
To play local audio, pass a Microphone object as source. This captures and plays local
audio from the microphone hardware.
To play live or recorded audio streaming from the Flash Media Server, pass a NetStream
object as information. To play back video from a NetStream object, use the
source. (The same NetStream object can contain both audio and video
Video.attachVideo()
method.)
You don’t have to use this method to play back incoming streamed audio; audio sent through a stream is played through the subscriber’s standard audio output device by default when the subscriber issues
NetStream.play(). However, if you use this method to route streaming
audio to a movie clip, you can then create a Sound object to control some aspects of the sound.
62 Client-Side ActionScript Language Reference
Example
The following example creates a new NetStream connection. Add a new Video symbol by opening the Library panel and selecting New Video from the Library options menu. Give the symbol the instance name
attachAudio() method to attach the audio from the FLV file to a movie clip on the Stage.
my_video. Dynamically load the FLV video at runtime. Use the
Then you can control the audio in the movie clip by using the Sound class and two buttons called
volUp_btn and volDown_btn.
var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(my_ns); my_ns.play("yourVideo.flv"); this.createEmptyMovieClip("flv_mc", this.getNextHighestDepth()); flv_mc.attachAudio(my_ns); var audio_sound:Sound = new Sound(flv_mc);
// Add volume buttons. volUp_btn.onRelease = function() { if (audio_sound.getVolume()<100) { audio_sound.setVolume(audio_sound.getVolume()+10); updateVolume(); } }; volDown_btn.onRelease = function() { if (audio_sound.getVolume()>0) { audio_sound.setVolume(audio_sound.getVolume()-10); updateVolume(); } };
// updates the volume this.createTextField("volume_txt", this.getNextHighestDepth(), 0, 0, 100,
22);
updateVolume(); function updateVolume() { volume_txt.text = "Volume: "+audio_sound.getVolume(); }
The following example specifies a microphone as the audio source for a dynamically created movie clip instance called
var active_mic:Microphone = Microphone.get(); this.createEmptyMovieClip("audio_mc", this.getNextHighestDepth()); audio_mc.attachAudio(active_mic);
audio_mc:
MovieClip class 63
The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
See also
Microphone class, NetStream class, NetStream.attachAudio(), Sound class in
MovieClip.getNextHighestDepth() method.
ActionScript 2.0 Language Reference
NetConnection class
Availability
Flash Player 6.
NOTE
In Flash Player 7 and later, you can use this class to open a connection and play FLV files without Flash Media Server. For more information, see the Netconnection class entry in ActionScript 2.0 Language Reference.
The NetConnection class manages a bidirectional connection between Flash Player and a server, which lets you connect to Flash Remoting or to Flash Media Server. Flash Media Server enables you to share audio, video, and data using the Macromedia Real-Time Messaging Protocol (RTMP).
For information on using Flash with an application server, see http://www.macromedia.com/
go/flashmediaserver_desdev_en. For information on using Flash with Flash Media Server, see
the following entries in addition to NetConnection:
NetStream class—for any RTMP communication
Camera class—for capturing and transmitting video
Microphone class—for capturing and transmitting audio
SharedObject class—for sharing data
Video class—for displaying video
For information on creating a NetConnection object, see “Constructor for the
NetConnection class” on page 65.
64 Client-Side ActionScript Language Reference
Method summary for the NetConnection class
Method Description
NetConnection.call() Invokes a command or method on the server.
NetConnection.close() Closes the connection with the server.
NetConnection.connect() Connects to an application on the Flash Media Server.
Property summary for the NetConnection class
Property (read-only) Description
NetConnection.isConnected Read-only; a Boolean value that indicates whether Flash
Player is connected to the server ( through the specified connection.
NetConnection.uri Read-only; the target URI that was passed in with
NetConnection.connect().
true) or not (false)
Event handler summary for the NetConnection class
Method Description
NetConnection.onStatus Invoked when a status change or error is posted for the
NetConnection object.
Constructor for the NetConnection class
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
new NetConnection()
Parameters
None.
Returns
A NetConnection object.
NetConnection class 65
Description
Constructor; creates an object that can be used to connect Flash Player to the Flash Media Server or to an application server. After creating the NetConnection object, use
NetConnection.connect() to make the actual connection.
For information on using Flash with an application server, see http://www.macromedia.com/
go/flashmediaserver_desdev_en.
Example
The following doConnect() function uses the NetConnection constructor to create a new connection and connect to the server:
function doConnect() {
// Make a new connection object. var my_nc:NetConnection = new NetConnection();
/* Get the name of the server from user input and assign it to a variable named myURL. */ var myURL_str:String = serverName;
// Connect to the service. my_nc.connect("rtmp://" + myURL_str + "/someApp/someInstance");
}
See also
NetConnection.connect()
NetConnection.call()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
call(remoteMethod, resultObject | null [, p1,...,pN])
Parameters
remoteMethod A parameter in the form [/objectPath/]method; if you are calling a
method on a NetConnection object, you can omit
someObj/doSomething
application passed to specified
p1,...,pN parameters.
means the server must call the someObj.doSomething method of the
NetConnection.connect() in its targetURI parameter, passing the
objectPath. For example, the parameter /
66 Client-Side ActionScript Language Reference
For security reasons, certain remoteMethod names are reserved at the application level; do not call these method names with the
onConnect
resultObject An object parameter that is needed only when the sender is expecting a
, /onDisconnect, /onStatus, /onAppStop, and /onAppStart.
NetConnection.call method(). The reserved names are /
result. The result object can be any user-defined object. For it to be of use, a handler named
onResult must be called when the result arrives. If you don’t need a result object, pass null.
p1,...pN Optional parameters to be passed to the specified method.
Returns
Nothing.
Description
Method; invokes a command or method on the server. You must create a server-side function to define this method. This method is also used when your application connects to an application server. For information on using Flash with an application server, see http://
www.macromedia.com/go/flashmediaserver_desdev_en.
Example
The following function checks for a message, sends it, then clears the local string.
function mySend(){
if (length(msg) > 0) {
my_nc.call("message", null, msg); } msg = "";
}
NetConnection.close()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public close() : Void
Parameters
None.
Returns
Nothing.
NetConnection class 67
Description
Method; closes the connection with the server and invokes NetConnection.onStatus with a
code property of NetConnection.Connect.Close. For more information, see
NetConnection.onStatus.
This method disconnects all NetStream objects running over this connection; any queued data that has not been sent is discarded. (To terminate server streams without closing the connection, use
NetStream.close().) If you want to reconnect, you must recreate the
NetStream object (see “Constructor for the NetStream class” on page 79).
This method also disconnects all remote shared objects running over this connection. However, you don’t need to recreate the shared object to reconnect. Instead, you can just call
SharedObject.connect() to reestablish the connection to the shared object. Also, any data
in the shared object that was queued when you issued
NetConnection.close() will be sent
after you reestablish a connection to the shared object.
Example
The following disconnect() function stops the published stream, then calls
NetConnection.close() to delete the source connection. With no source stream to play, the
destination stream automatically ends and is deleted.
function disconnect() {
// stops publishing the stream srcStream_ns.close();
// deletes the source stream connection my_nc.close();
}
See also
NetConnection.connect(), NetConnection.onStatus, NetStream.close(),
SharedObject.connect()
NetConnection.connect()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public connect(targetURI:String) : Boolean
68 Client-Side ActionScript Language Reference
Parameters
targetURI The Uniform Resource Identifier (URI) of the application on the Flash Media
Server that runs when the connection is made. For
targetURI, use the following general
format (items in brackets are optional):
protocol:[//host][:port]/appname/[instanceName]
For protocol, specify either rtmp, rtmpt, or rtmps. If rtmp is specified, Flash Player will create a persistent socket connection with Flash Media Server. If Player will create an HTTP “tunneling” connection to the server. If
rtmpt is specified, Flash
rtmps is specified, Flash
Player will create a secure connection to the server. For more information on RTMP, RTMPT, and RTMPS, see the description section below.
You can omit the
host parameter if the SWF file is served from the same host where Flash
Media Server is installed.
If the
instanceName parameter is omitted, Flash Player connects to the application’s default
instance (
_definst_).
By default, RTMP connections use port 1935, and RTMPT connections use port 80.
For example, the following URIs are formatted correctly:
rtmp://www.myCompany.com/myMainDirectory/groupChatApp/HelpDesk
rtmpt:/sharedWhiteboardApp/June2002
rtmp::1234/chatApp/room_name
p1 ... pN Optional parameters of any type to be passed to the application specified in targetURI. If the application is unable to process the parameters in the order in which they
are received,
NetConnection.Connect.Rejected.
NetConnection.onStatus is invoked with the code property set to
Returns
A Boolean value of true if you passed in a valid URI; otherwise, false. (To determine if the connection was successfully completed, use
NetConnection.onStatus.)
Description
Method; connects to an application on the Flash Media Server. This method can also be used to communicate with an application server. For information, see http://
www.macromedia.com/go/flashmediaserver_desdev_en.
NetConnection class 69
In general, use the RTMP protocol, which opens a persistent connection between Flash Player and Flash Media Server. If, however, clients are connecting from behind a firewall or through HTTP proxy servers that prohibit direct RTMP socket connections, use the RTMPT protocol, which transmits RTMP data over an HTTP connection. The RTMPT protocol explicitly requests an HTTP connection and enables a faster connection time for clients who can’t connect through RTMP.
RTMPS connections use port 443 by default.
If Flash Player fails to connect to the server over an RTMP connection on the default port, it will automatically try to establish a connection using a predetermined sequence of ports and protocols. For example, if an application tries and fails to connect using
my_nc.connect("rtmp:/myserver/myapp"), Flash Player will automatically try the
following sequence of connections, until successful:
my_nc.connect("rtmp://myserver:443/myapp"); my_nc.connect("rtmp://myserver:80/myapp"); my_nc.connect("rtmpt://myserver:80/myapp");
This connection sequence can enable connections to succeed that otherwise would not. However, during this connection sequence users may wait several seconds for multiple connection attempts to time out.
NOTE
This automatic retry sequence will occur only if the initial connection specifies the RTMP protocol and uses the default port—for example,
myapp")
.
my_nc.connect("rtmp:/myserver/
If you want to use this connection for publishing or playing audio or video in real time, or to publish or play previously recorded audio or video streams, you must connect to the Flash Media Server and then create a NetStream object within this NetConnection object. For more information, see the NetStream class entry.
If you want to use this connection for synchronizing data among multiple clients or between the client and a server, you must connect to the Flash Media Server and then create a remote shared object within this NetConnection object. For more information, see the SharedObject
class entry.
When you call this method, the
NetConnection.onStatus event handler is invoked with an
information object that specifies whether the connection succeeded or failed. For more information, see
NetConnection.isConnected is set to true.
70 Client-Side ActionScript Language Reference
NetConnection.onStatus. If the connection is successful,
Because of network and thread timing issues, it is better to place a NetConnection.onStatus handler in a script before a might complete before the script executes the security checks are made within the will be lost if the
onStatus handler is not yet set up.
NetConnection.connect() method. Otherwise, the connection
onStatus handler initialization. Also, all
NetConnection.connect() method, and notifications
If the specified connection is already open when you call this method, an implicit
NetConnection.close() method is invoked, and then the connection is reopened.
During the connection process, any server responses to subsequent
NetStream.send(), or SharedObject.send() methods are queued until the server
authenticates the connection and
NetConnection.onStatus is invoked. The call or send
NetConnection.call(),
methods are then processed in the order received. Any pending updates to remote shared objects are also queued until the connection is successful, at which point they are transmitted to the server.
Video and audio, however, are not queued during the connection process. Any video or audio that is streaming from the server is ignored until the connection is successfully completed. For example, confirm that the connection was successful before enabling a button that calls the
NetStream.publish() method.
If your connection fails, make sure you have met all the requirements for connecting successfully:
You are specifying the correct protocol name for connecting to the server (rtmp, or rtmpt,
for the Flash Media Server).
You are connecting to a valid application on the correct server.
You have a subdirectory in the Flash Media Server applications directory with the same
name as the application specified in the connection URL.
The server is running.
To distinguish among different instances of a single application, pass a value for
instanceName as part of targetURI. For example, you may want to give different groups of
people access to the same application without having them interact with each other. To do so, you can open multiple chat rooms at the same time, as shown below.
my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew") my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoKnit")
NetConnection class 71
In another case, you may have an application named lectureSeries that records and plays back classroom lectures. To save individual lectures, pass a different value for
instanceName
each time you record a lecture, as shown in the following example:
// Record Monday’s lecture. my_nc.connect("rtmp://www.myserver.com/lectureSeries/Monday"); // Later ... my_ns.connect(my_nc); my_ns.publish("lecture", "record");
// Record Tuesday’s lecture. my_nc.connect("rtmp://www.myserver.com/lectureSeries/Tuesday"); // Later ... my_ns.connect(my_nc); my_ns.publish("lecture", "record"); // and so on
// Play back one of the lectures. my_nc.connect("rtmp://www.myserver.com/lectureSeries/Monday"); // Later ... my_ns.connect(my_nc); my_ns.play("lecture")
You can also nest instance names, as shown in the following example:
my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew/Monday") my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew/Tuesday")
For information on where recorded streams are stored on the server, see
NetStream.publish().
Understanding file naming and domains used with this method If an HTML page
containing a SWF file is accessed differently (with regards to domain names) from the way the SWF file itself accesses the Flash Media Server, then the connection will not be successful. This is a security feature of Flash Player. But in some cases, this may be inconvenient.
For example, if a web page containing a SWF file is served on an intranet from, say, http:// deptserver.mycorp.com, it can also be accessed simply by http://deptserver. If the page is accessed via, say, http://deptServer/tcpage.htm, but the SWF file specifies deptServer.mycorp.com in
targetURI, then the SWF file will not make a successful
connection to the server. Similarly, if the web page and SWF file are accessed as http:// deptserver.mycorp.com/tcpage.htm, but the SWF file specifies rtmp://deptserver in
targetURI, it will not connect.
72 Client-Side ActionScript Language Reference
There are a few things you can do to prevent the security policies from inconveniencing you or your users. The first, and easiest, is to use a target URI that doesn’t specify a server name. (This is applicable only if the Flash Media Server and web server are running from the same IP address.) To do so, leave off the second slash in the
targetURI parameter. For example, the
following commands will make Flash Player attempt to connect to the same host and domain as the web server the SWF file was served from:
my_nc = new NetConnection(); my_nc.connect("rtmp:/myApp");
Second, there is a bit of JavaScript you can use in your HTML page to avoid the security problem. Assuming the SWF file uses a fully qualified domain name URL to access the Flash Media Server, this JavaScript redirects the web page to an explicitly named full URL, like this:
<SCRIPT language="javascript"> //if the URL didn't have the domain on it if (document.URL.indexOf("mycorp.com") == -1) { //redirect to a version that does document.URL="http://deptServer.mycorp.com/tcpage.htm"; } </script>
Finally, if you own a domain name, have access to the DNS records of that domain name, and have a static IP address for your Flash Media Server, you can create address (“A”) records to point a host name to that IP address. For instance, flashcom.mycorp.com could map to the machine running the Flash Media Server and having an IP address provided by your IT department or ISP. Your web pages can continue to be hosted by whatever means you are currently using. (“CNAME” records are recommended if you need to forward traffic to a server that has a DNS-accessible host name but may or may not have a static IP address.)
Example
The following example connects over the RTMP protocol to the default instance of the
funAndGames application located on the real host of the macromedia server using the default
port:
my_nc = new NetConnection(); my_nc.connect("rtmp://real.macromedia.com/funAndGames");
The following example connects over the RTMPT protocol to the room_01 application instance of the
chat application using the default port. In this example, the Flash SWF file is
served from the same host and domain as Flash Media Server, so the host parameter is omitted.
my_nc = new NetConnection(); my_nc.connect("rtmpt:/chat/room_01");
NetConnection class 73
The following example opens a connection to play the video2.flv file. Select New Video from the Library options menu to create a new Video object, and give it the instance name
my_video.
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("video2.flv");
See also
NetConnection.close(), NetConnection.onStatus
NetConnection.isConnected
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
my_nc.isConnected
Description
Property (read-only); a Boolean value indicating whether Flash Player is connected to the server (
true) or not (false) through the specified connection. Whenever a connection is
made or closed, this property is set.
Example
The following example is attached to a toggle push button. When the user clicks the button, if the user is connected to the server, the connection is closed. If the user is not connected, a connection is established.
on (release) {
if (_root.my_nc.isConnected == true)
_root.my_nc.close(); else
_root.my_nc.connect(_root.myURI);
}
See also
NetConnection.close(), NetConnection.connect(), NetConnection.onStatus
74 Client-Side ActionScript Language Reference
NetConnection.onStatus
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
my_nc.onStatus = function(infoObject) {
// your code here
}
Parameters
infoObject A parameter defined according to the status message. For more information
about this parameter, see “NetConnection information objects” on page 152.
Returns
Nothing.
Description
Event handler; invoked when a status change or error is posted for the NetConnection object. If you want to respond to this event handler, you must create a function to process the information object sent by the server. For more information, see “Client-Side Information
Objects” on page 149.
Example
The following example writes data about the connection to a log file.
reconnection_nc.onStatus = function(info){
_root.log += "Recording stream status.\n"; _root.log += "Event: " + info.code + "\n"; _root.log += "Type: " + info.level + "\n"; _root.log += "Message:" + info.description + "\n";
}
See also
NetConnection.call(), NetConnection.close(), NetConnection.connect()
NetConnection.uri
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
NetConnection class 75
Usage
my_nc.uri
Description
Property (read-only); a string representing the target URI that was passed in with
NetConnection.connect(). If NetConnection.connect() hasn’t yet been called for my_nc,
this property is undefined.
See also
NetConnection.connect()
NetStream class
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
NOTE
In Flash Player 7 and later, you can use this method to play FLV files without Flash Media Server. For more information, see the NetStream class entry in ActionScript
2.0 Language Reference.
The NetStream class opens a one-way streaming connection between Flash Player and Flash Media Server 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 receive data, using
NetStream.publish(), or subscribe to a published stream and
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
NetStream.send()).
The following steps summarize the sequence of actions required for publishing real-time audio and video using Flash Media Server and the Real-Time Messaging Protocol (RTMP):
1. Use new NetConnection to create a NetConnection object.
2. Use NetConnection.connect("rtmp://serverName/appName/appInstanceName") to
connect the application instance to the Flash Media Server.
3. Use new NetStream(connection:String) to create a data stream over the connection.
4. Use NetStream.attachAudio(audioSource:Microphone) to capture and send audio
over the stream, and
NetStream.attachVideo(videoSource:Camera) to capture and
send video over the stream.
76 Client-Side ActionScript Language Reference
5. Use NetStream.publish(publishName:String) to give this stream a unique name and
send data over the stream to the Flash Media Server, so 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 specified here; that is, they will call the same
NetStream.play(publishName:Object) method. They will also have to call
Video.attachVideo() to display the video.
NetConnection.connect() method as the publisher, and then call a
Multiple streams can be open simultaneously over one connection, but each stream either publishes or plays. To publish and play over a single connection, open two streams over the connection, as shown in the following example. This example publishes audio and video data in real time on one stream and plays it back on another stream on the same client, through the same connection.
// These lines begin broadcasting. var my_nc:NetConnection = new NetConnection(); // Create connection object. my_nc.connect("rtmp://mySvr.myDomain.com/App"); // Connect to server. publish_ns:NetStream = new NetStream(my_nc); // Open stream within
connection.
publish_ns.attachAudio(Microphone.get()); // Capture audio. publish_ns.attachVideo(Camera.get()); // Capture video. publish_ns.publish("todays_news"); // Begin broadcasting.
/* These lines open a stream to play the video portion of the broadcast
inside a Video object named my_video. The audio is played through the standard output device--you don’t need to issue a separate command to hear the audio. */
var play_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(play_ns); // Specify where to display video. play_ns.play("todays_news"); // play() uses the same name as publish()
above.
In the previous example, notice that both the publisher and subscriber call an attachVideo() method. The publisher calls The subscriber calls
Video.attachVideo() to connect a video feed to a Video object on the
NetStream.attachVideo() to connect a video feed to a stream.
Stage; the incoming video is displayed inside this object.
Keep in mind also that although the publisher calls an
attachAudio() method, the
subscriber does not. This is because audio sent through a stream is played through the subscriber’s standard audio output device by default; the subscriber doesn’t have to attach the incoming audio to an object on the Stage. However, you can use
MovieClip.attachAudio()
to route audio from a NetStream object to a movie clip. If you do this, you can then create a Sound object to control the volume of the sound. For more information, see
MovieClip.attachAudio().
NetStream class 77
Method summary for the NetStream class
Method Description
NetStream.attachAudio() Publisher method; specifies whether audio should be sent
over the stream.
NetStream.attachVideo() Publisher method; starts transmitting video or a snapshot
from the specified source.
NetStream.close() Stops publishing or playing all data on the stream and
makes the stream available for another use.
NetStream.pause() Subscriber method; pauses or resumes playback of a
stream.
NetStream.play() Subscriber method; feeds streaming audio, video, and text
messages being published on the Flash Media Server, or a recorded file stored on the server, to the client.
NetStream.publish() Publisher method; sends streaming audio, video, and text
messages from the client to the Flash Media Server, optionally recording the stream during transmission.
NetStream.receiveAudio() Subscriber method; specifies whether incoming audio plays
on the stream.
NetStream.receiveVideo() Subscriber method; specifies whether incoming video will
play on the stream, or specifies the frame rate of the video.
NetStream.seek() Subscriber method; seeks to a position in the recorded
stream currently playing.
NetStream.send() Publisher method; broadcasts a message to all subscribing
clients.
NetStream.setBufferTime() Method; for a publishing stream, this number indicates how
long the outgoing buffer can grow before Flash starts dropping frames. For a subscribing stream, this number indicates how long to buffer incoming data before starting to display the stream.
78 Client-Side ActionScript Language Reference
Property summary for the NetStream class
Property (read-only) Description
NetStream.bufferLength The number of seconds of data currently in the buffer.
NetStream.bufferTime The number of seconds assigned to the buffer by
NetStream.setBufferTime().
NetStream.currentFps The number of frames per second being sent or received on
the publishing or subscribing stream.
NetStream.liveDelay The number of seconds of data in a subscribing stream’s
buffer in live mode.
NetStream.time The number of seconds a stream has been playing or
publishing.
Event handler summary for the NetStream class
Method Description
NetStream.onCuePoint Invoked when an embedded cue point is reached while
playing an FLV file.
NetStream.onMetaData Invoked when the Flash Player receives descriptive
information embedded in the FLV file being played.
NetStream.onPlayStatus Invoked when a NetStream object has completely played a
stream.
NetStream.onStatus Invoked every time a status change or error is posted for the
NetStream object.
Constructor for the NetStream class
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
new NetStream(connection)
Parameters
connection A NetConnection object.
NetStream class 79
Returns
A NetStream object.
Description
Constructor; creates a stream that can be used for publishing (sending) or playing (receiving) data through the specified NetConnection object.
You can’t publish and play data over the same stream at the same time. For example, if you are publishing on a stream and then call
NetStream.play(), an implicit NetStream.close()
method is called; the publishing stream then becomes a subscribing stream.
However, you can create multiple streams that run simultaneously over the same connection: one stream publishes and another stream plays.
Example
The following example shows how a publishing client and a subscribing client can connect to the Flash Media Server and then open an application stream for sending (publishing) or receiving (playing) data over this connection.
// Publishing client contains this code. my_nc:NetConnection = new NetConnection(); // create NetConnection
object
my_nc.connect("rtmp://myRTMPServer.myDomain.com/app"); // connect to server
my_ns:NetStream = new NetStream(my_nc); // open app stream within my_nc my_ns.publish("myWeddingVideo"); // publish data over this stream
// Subscribing client contains this code. /* Note that the connection and stream names are the same as those used by
the publishing client. This is neither required nor prohibited,because the scripts are running on different machines.However,the parameters used with connect() and play() below must be the same as those used with connect() and publish() above. */
my_nc:NetConnection = new NetConnection(); my_nc.connect("rtmp://myRTMPServer.myDomain.com/app");
my_ns:NetStream = new NetStream(my_nc); my_ns.play("myWeddingVideo");
For more examples, see the NetStream class entry and Video.attachVideo().
See also
NetConnection class, NetStream.attachAudio(), NetStream.attachVideo(), NetStream.play(), NetStream.publish(), Video.attachVideo()
80 Client-Side ActionScript Language Reference
NetStream.attachAudio()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public attachAudio(source:Microphone) : Void
Parameters
source The source of the audio to be transmitted. Valid values are a Microphone object
and
null.
Returns
Nothing.
Description
Method; specifies whether audio should be sent over the stream (from a Microphone object passed as publisher of the specified stream.
source) or not (null passed as source). This method is available only to the
You can call this method before or after you call the
NetStream.publish() method and
actually begin transmitting. Subscribers who want to hear the audio must call a
NetStream.play() method.
Subscribers can also attach their incoming audio to a movie clip and then create a Sound object to control some aspects of the sound. For more information, see
MovieClip.attachAudio().
Example
The following code attaches a microphone to a network stream:
my_netstream.attachAudio(active_mic);
See also
Microphone class, MovieClip.attachAudio(), NetStream.attachVideo(), NetStream.publish(), NetStream.receiveAudio()
NetStream class 81
NetStream.attachVideo()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public attachVideo(source : Camera [, snapShotMilliseconds : Number])
Parameters
source The source of the video transmission. Valid values are a Camera object (which starts
capturing video) and parameters you send are ignored.
snapShotMilliseconds An optional integer 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 captures all video until you issue
my_ns.attachVideo(null).
If you pass 0, Flash captures only a single video frame. Use this value to transmit
“snapshots” within a preexisting stream.
NOTE
Flash interprets invalid, negative, or nonnumeric arguments as 0.
null. If you pass null, Flash stops capturing video, and any additional
If you pass a positive number, Flash captures a single video frame and then appends a
pause of length
snapShotMilliseconds as a “trailer” on the snapshot. Use this value to
create time-lapse photography effects.
Returns
Nothing.
Description
Method; starts capturing video from the specified source, or stops capturing if source is
null. This method is available only to the publisher of the specified stream.
82 Client-Side ActionScript Language Reference
After attaching the video source, you must call NetStream.publish() to actually begin transmitting. Subscribers who want to display the video must call the
Video.attachVideo() methods to display the video on the Stage.
NetStream.play() and
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 length of time the video message is displayed. By repeatedly calling positive value for
snapShotMilliseconds, the snapshot/trailer/snapshot/trailer... sequence
attachVideo with a
creates time-lapse footage. For example, you could capture one frame per day and append it to a video file. When a subscriber plays back the file, each frame remains onscreen for the specified number of milliseconds and then the next frame is displayed.
The
snapShotMilliseconds parameter serves a different purpose from the fps parameter
you can set with
Camera.setMode(). When you specify snapShotMilliseconds, you are
controlling how much time elapses during playback between recorded frames. When you specify
fps using Camera.setMode(), you are controlling how much time elapses during
recording and playback between recorded frames.
For example, suppose you want to take a snapshot every 5 minutes for a total of 100 snapshots. You can do this in two different ways:
You c an iss ue a NetStream.attachVideo(source, 500) command 100 times, once
every 5 minutes. This takes 500 minutes to record, but the resulting file will play back in 50 seconds (100 frames with 500 milliseconds between frames).
You c an iss ue a Camera.setMode() command with an fps value of 1/300 (one per 300
seconds, or one every 5 minutes), and then issue a
NetStream.attachVideo(source)
command, letting the camera capture continuously for 500 minutes. The resulting file will play back in 500 minutes—the same length of time that it took to record—with each frame being displayed for 5 minutes.
Both techniques capture the same 500 frames, and both approaches are useful; which 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.
NetStream class 83
Example
The following function publishes a stream on a NetConnection named my_nc containing the camera output from
function pubLive() {
// Create a new source stream. var source_ns:NetStream = new NetStream(my_nc);
/* Attach the camera activity to the source stream. This call causes a warning message to show which service is requesting access. It also gives the user the option of not sending the camera activity to the server. */ source_ns.attachVideo(active_cam);
// Get the stream name from the user input. var mySubj:String = subject;
/* Assuming the user named the stream 'webCamStream', publish the live camera activity as 'webCamStream'. */ source_ns.publish(mySubj, "live");
}
active_cam.
See also the example for MovieClip.attachAudio().
See also
Camera class, Camera.setMode(), NetStream.publish(), NetStream.receiveVideo(), Video.attachVideo()
NetStream.bufferLength
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public bufferLength : Number [read-only]
Description
Property (read-only); the number of seconds of data currently in the buffer. You can use this property in conjunction with being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer.
NetStream.bufferTime to estimate how close the buffer is to
84 Client-Side ActionScript Language Reference
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 v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
MovieClip.getNextHighestDepth() method, which is used in this example.
See also
NetStream.bufferTime
NetStream.bufferTime
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public bufferTime : Number [read-only]
NetStream class 85
Description
Property (read-only); the number of seconds assigned to the buffer by
NetStream.setBufferTime(). The default value is 9. To determine the number of seconds
currently in the buffer, use
NOTE
The default value for Flash Media Server bufferTime property is different from the default value for the standard ActionScript bufferTime property.
NetStream.bufferLength.
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 the 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 v2 component (version 2 of the Macromedia Component Architecture), use the DepthManager class from the component framework instead of the
MovieClip.getNextHighestDepth() method, which is used in this example.
See also
NetStream.bufferLength, NetStream.setBufferTime()
86 Client-Side ActionScript Language Reference
NetStream.close()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public close() : Void
Parameters
None.
Returns
Nothing.
Description
Method; stops publishing or playing all data on the stream, sets the NetStream.time property to 0, and makes the stream available for another use. This method is invoked implicitly whenever you call
NetStream.publish() from a subscribing stream.
NetStream.play() from a publishing stream, or
If this method is called from a publishing stream, all pending NetStream.play() calls on
the stream are cleared on the server; subscribers no longer receive anything that was being published on the stream.
If this method is called from a subscribing stream, publishing continues and other
subscribing streams may still be playing, but the subscriber can now use the stream for another purpose.
To stop play on a subscribing stream without closing the stream or changing the stream
type, use
my_ns.play(false).
Example
The following onDisconnect() function closes a stream:
function onDisconnect() {
// Stops publishing the stream. srcStream_ns.close();
/* Deletes the source stream connection. With no source to play, the destination stream also ends and can be deleted. */ my_nc.close();
}
NetStream class 87
See also
NetStream.pause(), NetStream.play(), NetStream.publish(), NetStream.time
NetStream.currentFps
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public currentFps : Number [read-only]
Description
Property (read-only); the number of frames per second being sent or received on the specified publishing or subscribing stream.
NetStream.liveDelay
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public liveDelay : Number [read-only]
Description
Property (read-only); 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).
88 Client-Side ActionScript Language Reference
Example
The following example displays a string (inside a text field named connectionQuality_str) indicating the connection quality over the NetStream object named value of the
if (my_ns.liveDelay < .5) {
connectionQuality_str.text = "Good";
} else if (my_ns.liveDelay < 1) {
connectionQuality_str.text = "Slow";
} else {
connectionQuality_str.text = "Network congested";
}
liveDelay property.
my_ns, according to the
NetStream.onCuePoint
Availability
Flash Player 8.
Flash Media Server 2.
Usage
public onCuePoint = function(infoObject:Object) {}
Parameters
infoObject An object with the following properties:
Property Description
name
time
type
parameters
The name given to the cue point when it was embedded in the FLV file.
The time in seconds at which the cue point occurred in the video file during playback.
The type of cue point that was reached: either “navigation” or “event”.
An associative array of name/value pair strings specified for this cue point. Any valid string can be used for the parameter name or value.
NetStream class 89
Returns
Nothing.
Description
Event handler; invoked when an embedded cue point is reached while an FLV file is playing. 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.
The following are two types of cue points that can be embedded in an FLV file:
A navigation cue point specifies a keyframe within the FLV file; the cue point's time
property corresponds to that exact keyframe. Navigation cue points are often used as bookmarks or entry points to let users navigate through the video file.
An event cue point is specified by time, whether or not that time corresponds to a specific
keyframe. An event cue point usually represents a time in the video when something happens that could be used to trigger other application events.
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 the video begins playing. The
onMetaData event handler gets information about all of the cue points before
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
You can use the list of cue points provided to the
onCuePoint event handler to trigger some action in your code.
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.
90 Client-Side ActionScript Language Reference
Example
The code in this example starts by creating new NetConnection and NetStream objects. Then it defines the named property in the finds the property named
onCuePoint handler for the NetStream object. The handler cycles through each
infoObject object and prints the property's name and value. When it
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");
NetStream class 91
The code in this example 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
NetStream.onMetaData
NetStream.onMetaData
Availability
Flash Player 7.
Flash Media Server 2.
Usage
public onMetaData = function(infoObject:Object) {}
Parameters
infoObject An object containing one property for each metadata item.
Returns
Nothing.
92 Client-Side ActionScript Language Reference
Description
Event handler; invoked when the Flash Player receives descriptive information embedded in the FLV file being played.
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 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.
Example
The code in this example starts by creating new NetConnection and NetStream objects. Then it defines the every named property in the
onMetaData() handler for the NetStream object. The handler cycles through
infoObject object that is received 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");
The code in this example 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 varies depending on the software that was used to encode the FLV file.
NetStream class 93
NetStream.onPlayStatus
Availability
Flash Player 6.
Flash Media Server 2.
Usage
public onPlayStatus = function(infoObject:Object) {}
Parameters
infoObject An object containing an error or status message. For more information about
this parameter, see “NetStream information objects” on page 153.
Returns
Nothing.
Description
Event handler; invoked when a NetStream object has completely played a stream. The information object gives extra information when a NetStream object has switched from one stream to another stream in a playlist ( has played to the end (
NetStream.Play.Complete). If you want to respond to this event
handler, you must create a function to process the information object sent by the server. For more information, see Appendix A, “Client-Side Information Objects,” on page 149.
NetStream.Play.Switch) or when a NetStream object
Example
The following example displays data about the stream in the Output panel:
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"); stream_ns.onPlayStatus = function(infoObject:Object) { trace("NetStream.onPlayStatus called: ("+getTimer()+" ms)"); for (var prop in infoObject) {
trace("\t"+prop+":\t"+infoObject[prop]); } trace("");
};
94 Client-Side ActionScript Language Reference
NetStream.onStatus
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public onStatus = function(infoObject:Object) {}
Parameters
infoObject A parameter defined according to the status or error message. For more
information about this parameter, see “NetStream information objects” on page 153.
Returns
Nothing.
Description
Event handler; 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 sent by the server. For more information, see “Client-Side Information
Objects” on page 149.
In addition to this
System.onStatus. If NetStream.onStatus is invoked for a particular object and there is no
function assigned to respond to it, Flash processes a function assigned to
NetStream.onStatus handler, Flash also provides a super function called
System.onStatus if
it exists.
Example
The following example displays data about the stream in the Output panel:
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(""); };
NetStream class 95
NetStream.pause()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public pause( [ flag : Boolean] ) : Void
Parameters
flag 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.
Returns
Nothing.
Description
Method; pauses or resumes playback of a stream. This method is available only to clients subscribed to the specified stream, not to the stream’s publisher.
The first time you call this method on a given playlist (without sending a parameter), it pauses the playlist; 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.
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
96 Client-Side ActionScript Language Reference
In the following example, suppose you have a playlist of three recorded streams.
var my_nc:NetConnection = new NetConnection(); my_nc.connect("rtmp://localhost/appName/appInstance");
// Create a NetStream for playing back in a Video object named my_video. var my_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(my_ns);
// to play record1 my_ns.play("record1", 0, -1, false);
// to play record2 my_ns.play("record2", 0, -1, false);
// to play record3 my_ns.play("record3", 0, -1, false);
// You click a button to pause while record2 is playing. my_ns.pause();
// Later, you want to resume the play. my_ns.pause();
// Later, you want to start a new playlist.
// to play record4 my_ns.play("record4", 0, -1, true);
// to play record5 my_ns.play("record5", 0, -1, false);
// to play record6 my_ns.play("record6", 0, -1, false);
See also
NetStream.close(), NetStream.play()
NetStream class 97
NetStream.play()
Availability
Flash Player 6.
Flash Communication Server MX 1.0.
Usage
public play(name : Object [,start : Number[, len : Number[, reset :
Object]]])
Parameters
name An identifying name for live data published by NetStream.publish(), a recorded file
name for playback, or parameters you send are ignored.
To play back FLV files, the default Flash file format for recorded streams, specify the name of the stream without a file extension (for example, you’ve stored on the server or the ID3 tags of MP3 files, you must precede the stream name with
mp3: or id3:—for example, "mp3:bolero" or "id3:bolero". For more information on
playing MP3 files, see Developing Media Applications.
start An optional numeric parameter that specifies the start time, in seconds. This
parameter can also be used to indicate whether the stream is live or recorded.
false. If you pass false, the stream stops playing and any additional
"bolero"). To play back MP3 files that
The default value for start is -2, which means that Flash first tries to play the live stream
specified in stream specified in stream named
name. If a live stream of that name is not found, Flash plays the recorded
name. If neither a live nor a recorded stream is found, Flash opens a live
name, even though no one is publishing on it. When someone does begin
publishing on that stream, Flash begins playing it.
If you pass -1 for start, Flash plays only the live stream specified in name. If no live
stream is found, Flash waits for it indefinitely if value, Flash waits for
If you pass 0 or a positive number for start, Flash plays only a recorded stream named
name, beginning start seconds from the beginning of the stream. If no recorded stream is
len seconds before it begins playing the next item in the playlist.
len is set to -1; if len is set to a different
found, Flash begins playing the next item in the playlist immediately.
If you pass a negative number other than -1 or -2 for start, Flash interprets the value as
if it were -2.
98 Client-Side ActionScript Language Reference
len An optional numeric parameter that specifies the duration of the playback, in seconds.
The default value for len is -1, which means that Flash plays a live stream until it is no
longer available or plays a recorded stream until it ends.
If you pass 0 for len, Flash plays the single frame that is start seconds from the
beginning of a recorded stream (assuming
If you pass a positive number for len, Flash plays a live stream for len seconds after it
becomes available, or plays a recorded stream for
len seconds, playback ends when the stream ends.)
If you pass a negative number other than -1 for len, Flash interprets the value as
start is equal to or greater than 0).
len seconds. (If a stream ends before
if it were -1.
reset An optional Boolean value or number that specifies whether to flush any
previous playlist. If
name plays only after previous streams finish playing. You can use this technique to create a
dynamic playlist. If immediately. By default, the value is
reset is false (0), name is added (queued) in the current playlist; that is,
reset is true (1), any previous play calls are cleared and name is played
true.
You can also specify a value of 2 or 3 for the recorded stream files that contain message data. These values are analogous to passing (0) and
true (1), respectively: a value of 2 maintains a playlist, and a value of 3 resets the
playlist. However, the difference is that specifying 2 or 3 for
reset parameter, which is useful when playing
false
reset causes Flash Media Server
to return all messages in the recorded stream file at once, rather than at the intervals at which the messages were originally recorded (the default behavior).
This is especially useful for accessing log files recorded by Flash Media Server. For more information on Flash Media Server logging, see TechNote 16464.
Description
Method; feeds streaming audio, video, and text messages being published on the Flash Media Server, or a recorded file stored on the server, to the client. This method is available only to clients subscribed to the specified stream, not to the stream’s publisher.
To view video data, you must call
Video.attachVideo(); audio being streamed with the
video will be played automatically. If audio-only data is being streamed, you can use
MovieClip.attachAudio() to route streaming audio to a movie clip, and then create a
Sound object to control some aspects of the audio.
NetStream class 99
You can use the optional parameters of this method to control various aspects of playback behavior. The following table shows a few ways in which these values interact:
start len Flash Player behavior
(Default) (Default) Plays the live stream until it is no longer available. If a live
stream of the specified name is not found, Flash Player plays a recorded stream until it ends.
-2 19 Plays a live stream for up to 19 seconds after it becomes available. If a live stream of the specified name is not found, Flash Player plays a recorded stream for 19 seconds.
15 19 Plays a recorded stream for 19 seconds, beginning 15
seconds from the beginning of the stream.
15 (Default) Plays a recorded stream, beginning 15 seconds from the
beginning of the stream, until the stream ends.
-1 (Default) Plays a live stream until it is no longer available.
This method can invoke objects. For example, if the specified stream isn’t found,
code property of NetStream.Play.StreamNotFound. For more information, see
NetStream.onStatus.
NetStream.onStatus with a number of different information
NetStream.onStatus is called with a
If you want to create a dynamic playlist that switches among different live or recorded streams, call
play more than once and pass false for reset each time. Conversely, if you
want to play the specified stream immediately, clearing any other streams that are queued for play, pass
Example
true for reset.
The following examples show some ways to use this method to play back live or recorded streams.
Example 1:
var my_nc:NetConnection = new NetConnection(); my_nc.connect("rtmp://localhost/appName/appInstance");
var my_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(my_ns);
/* To play a live stream named "stephen" being published elsewhere using the default values -- start time is -2, length is -1, and flushPlaylists is true -- don’t pass any optional parameters.*/ my_ns.play("stephen");
/* to immediately play a recorded stream named record1
100 Client-Side ActionScript Language Reference
Loading...