Reviews & Opinions
Independent and trusted. Read before buy Macromedia Flex-flex Actionscript Language Reference!

Macromedia Flex-flex Actionscript Language Reference


Bookmark
Macromedia Flex-flex Actionscript Language Reference

Bookmark and Share

 

Macromedia Flex-flex Actionscript Language ReferenceAbout Macromedia Flex-flex Actionscript Language Reference
Here you can find all about Macromedia Flex-flex Actionscript Language Reference like manual and other informations. For example: review.

Macromedia Flex-flex Actionscript Language Reference manual (user guide) is ready to download for free.

On the bottom of page users can write a review. If you own a Macromedia Flex-flex Actionscript Language Reference please write about it to help other people.
[ Report abuse or wrong photo | Share your Macromedia Flex-flex Actionscript Language Reference photo ]

 

 

Manual

Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Manual - 1 page  Manual - 2 page  Manual - 3 page 

Download (English)
Macromedia Flex-flex Actionscript Language Reference, size: 6.6 MB

 

Macromedia Flex-flex Actionscript Language Reference

 

 

User reviews and opinions

<== Click here to post a new opinion, comment, review, etc.

Comments to date: 3. Page 1 of 1. Average Rating:
Etrius 5:35pm on Sunday, October 31st, 2010 
Overkill for most basic networks or domains, but if virtualization is on your radar, then Hyper-V definitely something to consider. Another great piece of software from Microsoft. Due to the OEM licence the price is right too None
Guilmon 1:09am on Friday, August 20th, 2010 
Not really This book is more SBS 2008 for dummies than an administrators companion. Very comprehensive Very comprehensive book from the basics through to the more complex setup items. Depressingly big yet sparse Like the Windows Small Business Server "Pocket Companion". Perfect all round book for Server 2008 Just WOW! I have learnt more from this book in the past 4hrs than I have in the past year.
laughing_penguin 5:02am on Thursday, July 1st, 2010 
Easy to setup ; Runs like a Win 7 Desktop No real cons other than you need to know what you are doing or you can get into trouble real quick Im not sure why they other reviewer said it wont work with mail servers? I have mdaemon running fine on it for a corporate domain. Easy to install.

Comments posted on www.ps2netdrivers.net are solely the views and opinions of the people posting them and do not necessarily reflect the views or opinions of us.

 

Documents

doc0

Chapter 20: Working with video Basics of video. 397 Understanding the Flash Video (FLV) format Understanding the Video class Loading video files Streaming video files Controlling video playback Understanding cue points Using cue points. 398. 399
. 400. 400. 402. 403. 402
Writing callback methods for onCuePoint and onMetaData Using video metadata Capturing camera input Advanced topics Example: Video Jukebox

. 408. 408. 411. 418

Chapter 21: Working with sound Basics of working with sound. 424 Understanding the sound architecture. 426
Loading external sound files

. 427. 429. 430. 434

Working with embedded sounds Working with streaming sound files Playing sounds

. 431. 435

Security considerations when loading and playing sounds Controlling sound volume and panning Working with sound metadata Accessing raw sound data Capturing sound input Example: Podcast Player

. 437. 443

Chapter 22: Capturing user input Basics of user input. 450 Capturing keyboard input Capturing mouse input Example: WordSearch. 451. 453. 456
Chapter 23: Networking and communication Basics of networking and communication. 460 Working with external data Socket connections Storing local data. 462. 467 Connecting to other Flash Player and AIR instances
. 472. 475. 478. 488. 486
Working with file upload and download Example: Building a Telnet client
Example: Uploading and downloading files
Chapter 24: Client system environment Basics of the client system environment. 495 Using the System class. 496. 497. 498. 504 Using the Capabilities class Using the IME class
Using the ApplicationDomain class
Example: Detecting system capabilities
Chapter 25: Printing Basics of printing. 508 Printing a page. 509. 510. 512. 514. 516 Flash Player and AIR tasks and system printing Setting size, scale, and orientation Example: Multiple-page printing
Example: Scaling, cropping, and responding
Chapter 26: Using the external API Basics of using the external API. 518 External API requirements and advantages Using the ExternalInterface class. 519. 520
Example: Using the external API with a web page container Example: Using the external API with an ActiveX container

. 524. 529

Chapter 27: Flash Player security Flash Player security overview. 535 Overview of permission controls Security sandboxes Restricting networking APIs Full-screen mode security Loading content Cross-scripting Loading data. 537. 543. 545. 547

dynamic class Test {} var myTest:Test = new Test(); // function expression myTest.functionExp = function () { trace("Function expression") }; myTest.functionExp(); // Function expression delete myTest.functionExp; myTest.functionExp(); // error

ADOBE FLEX 3 77

If, on the other hand, the function is first defined with a function statement, it exists as its own object and continues to exist even after you delete the property to which it is attached. The delete operator only works on properties of objects, so even a call to delete the function stateFunc() itself does not work.
dynamic class Test {} var myTest:Test = new Test(); // function statement function stateFunc() { trace("Function statement") } myTest.statement = stateFunc; myTest.statement(); // Function statement delete myTest.statement; delete stateFunc; // no effect stateFunc();// Function statement myTest.statement(); // error
The second difference between function statements and function expressions is that function statements exist throughout the scope in which they are defined, including in statements that appear before the function statement. Function expressions, by contrast, are defined only for subsequent statements. For example, the following code successfully calls the scopeTest() function before it is defined:
statementTest(); // statementTest function statementTest():void { trace("statementTest"); }
Function expressions are not available before they are defined, so the following code results in a run-time error:
expressionTest(); // run-time error var expressionTest:Function = function () { trace("expressionTest"); } Returning values from functions
To return a value from your function, use the return statement followed by the expression or literal value that you want to return. For example, the following code returns an expression representing the parameter:
function doubleNum(baseNum:int):int { return (baseNum * 2); }
Notice that the return statement terminates the function, so that any statements below a return statement will not be executed, as follows:
function doubleNum(baseNum:int):int { return (baseNum * 2); trace("after return"); // This trace statement will not be executed. }
In strict mode, you must return a value of the appropriate type if you choose to specify a return type. For example, the following code generates an error in strict mode, because it does not return a valid value:
function doubleNum(baseNum:int):int { trace("after return"); }

function passPrimitives(xParam:int, yParam:int):void { xParam++; yParam++; trace(xParam, yParam); }

ADOBE FLEX 3 79

var xValue:int = 10; var yValue:int = 15; trace(xValue, yValue);// passPrimitives(xValue, yValue); // trace(xValue, yValue);// 10 15
Within the passPrimitives() function, the values of xParam and yParam are incremented, but this does not affect the values of xValue and yValue, as shown in the last trace statement. This would be true even if the parameters were named identically to the variables, xValue and yValue, because the xValue and yValue inside the function would point to new locations in memory that exist separately from the variables of the same name outside the function. All other objectsthat is, objects that do not belong to the primitive data typesare always passed by reference, which gives you ability to change the value of the original variable. For example, the following code creates an object named objVar with two properties, x and y. The object is passed as an argument to the passByRef() function. Because the object is not a primitive type, the object is not only passed by reference, but also stays a reference. This means that changes made to the parameters within the function will affect the object properties outside the function.
function passByRef(objParam:Object):void { objParam.x++; objParam.y++; trace(objParam.x, objParam.y); } var objVar:Object = {x:10, y:15}; trace(objVar.x, objVar.y); // passByRef(objVar); // trace(objVar.x, objVar.y); // 11 16
The objParam parameter references the same object as the global objVar variable. As you can see from the trace statements in the example, changes to the x and y properties of the objParam object are reflected in the objVar object.

Default parameter values

New in ActionScript 3.0 is the ability to declare default parameter values for a function. If a call to a function with default parameter values omits a parameter with default values, the value specified in the function definition for that parameter is used. All parameters with default values must be placed at the end of the parameter list. The values assigned as default values must be compile-time constants. The existence of a default value for a parameter effectively makes that parameter an optional parameter. A parameter without a default value is considered a required parameter. For example, the following code creates a function with three parameters, two of which have default values. When the function is called with only one parameter, the default values for the parameters are used.

ADOBE FLEX 3 241

One important consequence of this parameter involves working with display objects events. Normally, you might expect a display object to be removed from memory when it is removed from the display list. However, if other objects have subscribed as listeners to that display object, with the useWeakReference parameter set to false (the default), the display object will continue to exist in Flash Players or AIRs memory even though it no longer appears on the screen. To work around this issue, either have all the listeners subscribe to the display object with the useWeakReference parameter set to true, or else remove all the event listeners from the display object using the removeEventListener() method.

Removing event listeners

You can use the removeEventListener() method to remove an event listener that you no longer need. It is a good idea to remove any listeners that will no longer be used. Required parameters include the eventName and listener parameters, which are the same as the required parameters for the addEventListener() method. Recall that you can listen for events during all event phases by calling addEventListener() twice, once with useCapture set to true, and then again with it set to false. To remove both event listeners, you would need to call removeEventListener() twice, once with useCapture set to true, and then again with it set to false.

Dispatching events

The dispatchEvent() method can be used by advanced programmers to dispatch a custom event object into the event flow. The only parameter accepted by this method is a reference to an event object, which must be an instance of the Event class or a subclass of the Event class. Once dispatched, the target property of the event object is set to the object on which dispatchEvent() was called.
Checking for existing event listeners
The final two methods of the IEventDispatcher interface provide useful information about the existence of event listeners. The hasEventListener() method returns true if an event listener is found for a specific event type on a particular display list object. The willTrigger() method also returns true if a listener is found for a particular display list object, but willTrigger() checks for listeners not only on that display object, but also on all of that display list objects ancestors for all phases of the event flow.
Error events without listeners
Exceptions, rather than events, are the primary mechanism for error handling in ActionScript 3.0, but exception handling does not work for asynchronous operations such as loading files. If an error occurs during such an asynchronous operation, Flash Player and AIR dispatch an error event object. If you do not create a listener for the error event, the debugger versions of Flash Player and AIR will bring up a dialog box with information about the error. For example, using an invalid URL when loading a file produces this dialog box in the debugger version of Flash Player:

For more information on the Matrix class, see Using Matrix objects on page 313.

ADOBE FLEX 3 303

Using the Math class with drawing methods
A Graphics object draws circles and squares, but can also draw more complex forms, particularly when the drawing methods are used in combination with the properties and methods of the Math class. The Math class contains constants of common mathematical interest, such as Math.PI (approximately 3.14159265.), a constant for the ratio of the circumference of a circle to its diameter. It also contains methods for trigonometry functions, including Math.sin(), Math.cos(), and Math.tan() among others. Drawing shapes using these methods and constants create more dynamic visual effects, particularly when used with repetition or recursion. Many methods of the Math class expect circular measurements in units of radians rather than degrees. Converting between these two types of units is a common use of the Math class:
var degrees = 121; var radians = degrees * Math.PI / 180; trace(radians) // 2.111848394913139
The following example creates a sine wave and a cosine wave, to highlight the difference between the Math.sin() and Math.cos() methods for a given value.
var var var var var var sinWavePosition = 100; cosWavePosition = 200; sinWaveColor:uint = 0xFF0000; cosWaveColor:uint = 0x00FF00; waveMultiplier:Number = 10; waveStretcher:Number = 5;
var i:uint; for(i = 1; i < stage.stageWidth; i++) { var sinPosY:Number = Math.sin(i / waveStretcher) * waveMultiplier; var cosPosY:Number = Math.cos(i / waveStretcher) * waveMultiplier; graphics.beginFill(sinWaveColor); graphics.drawRect(i, sinWavePosition + sinPosY, 2, 2); graphics.beginFill(cosWaveColor); graphics.drawRect(i, cosWavePosition + cosPosY, 2, 2); }
Animating with the drawing API
One advantage of creating content with the drawing API is that you are not limited to positioning your content once. What you draw can be modified by maintaining and modifying the variables you use to draw. You can convey animation by changing variables and redrawing, either over a period of frames or with a timer. For example, the following code changes the display with each passing frame (by listening to the Event.ENTER_FRAME event), incrementing the current degree count, and directs the graphics object to clear and redraw with the updated position.
stage.frameRate = 31; var currentDegrees:Number = 0; var radius:Number = 40; var satelliteRadius:Number = 6; var container:Sprite = new Sprite(); container.x = stage.stageWidth / 2;

ADOBE FLEX 3 304

container.y = stage.stageHeight / 2; addChild(container); var satellite:Shape = new Shape(); container.addChild(satellite); addEventListener(Event.ENTER_FRAME, doEveryFrame); function doEveryFrame(event:Event):void { currentDegrees += 4; var radians:Number = getRadians(currentDegrees); var posX:Number = Math.sin(radians) * radius; var posY:Number = Math.cos(radians) * radius; satellite.graphics.clear(); satellite.graphics.beginFill(0); satellite.graphics.drawCircle(posX, posY, satelliteRadius); } function getRadians(degrees:Number):Number { return degrees * Math.PI / 180; }

Basics of movie clips

Introduction to working with movie clips
Movie clips are a key element for people who create animated content with the Flash authoring tool and want to control that content with ActionScript. Whenever you create a movie clip symbol in Flash, Flash adds the symbol to the library of that Flash document. By default, this symbol becomes an instance of the MovieClip class, and as such has the properties and methods of the MovieClip class. When an instance of a movie clip symbol is placed on the Stage, the movie clip automatically progresses through its timeline (if it has more than one frame) unless its playback is altered using ActionScript. It is this timeline that distinguishes the MovieClip class, allowing you to create animation through motion or shape tweens through the Flash authoring tool. By contrast, with a display object that is an instance of the Sprite class, you can create animation only by programmatically changing the objects values. In previous versions of ActionScript, the MovieClip class was the base class of all instances on the Stage. In ActionScript 3.0, a movie clip is only one of many display objects that can appear on the screen. If a timeline is not necessary for the function of a display object, using the Shape class or Sprite class in lieu of the MovieClip class may improve rendering performance. For more information on choosing the appropriate display object for a task, see Choosing a DisplayObject subclass on page 264.

Common movie clip tasks

The following common movie clips tasks are described in this chapter:
Making movie clips play and stop Playing movie clips in reverse Moving the playhead to specific points in a movie clips timeline Working with frame labels in ActionScript Accessing scene information in ActionScript Creating instances of library movie clip symbols using ActionScript

ADOBE FLEX 3 347

Loading and controlling external SWF files, including files created for previous Flash Player versions Building an ActionScript system for creating graphical assets to be loaded and used at run time
AVM1 SWF: A SWF file created using ActionScript 1.0 or ActionScript 2.0, usually targeting Flash Player 8 or earlier.

public function layoutColumns():void { if (this._text == "" || this._text == null) { return; } var field:TextField = fieldArray[0] as TextField; field.text = this._text; field.setTextFormat(this.format); this.preferredHeight = this.getOptimalHeight(field); var remainder:String = this._text; var fieldText:String = ""; var lastLineEndedPara:Boolean = true;

ADOBE FLEX 3 375

var indent:Number = this.format.indent as Number; for (var i:int = 0; i < fieldArray.length; i++) { field = this.fieldArray[i] as TextField; field.height = this.preferredHeight; field.text = remainder; field.setTextFormat(this.format); var lineLen:int; if (indent > 0 && !lastLineEndedPara && field.numLines > 0) { lineLen = field.getLineLength(0); if (lineLen > 0) { field.setTextFormat(this.firstLineFormat, 0, lineLen); } } field.x = i * (colWidth + gutter); field.y = 0; remainder = ""; fieldText = ""; var linesRemaining:int = field.numLines; var linesVisible:int = Math.min(this.linesPerCol, linesRemaining); for (var j:int = 0; j < linesRemaining; j++) { if (j < linesVisible) { fieldText += field.getLineText(j); } else { remainder +=field.getLineText(j); } } field.text = fieldText; field.setTextFormat(this.format); if (indent > 0 && !lastLineEndedPara) { lineLen = field.getLineLength(0); if (lineLen > 0) { field.setTextFormat(this.firstLineFormat, 0, lineLen); } } var lastLine:String = field.getLineText(field.numLines - 1); var lastCharCode:Number = lastLine.charCodeAt(lastLine.length - 1);

ADOBE FLEX 3 376

if (lastCharCode == 10 || lastCharCode == 13) { lastLineEndedPara = true; } else { lastLineEndedPara = false; } if ((this.format.align == TextFormatAlign.JUSTIFY) && (i < fieldArray.length - 1)) { if (!lastLineEndedPara) { justifyLastLine(field, lastLine); } } } }
After the preferredHeight property has been set by calling the getOptimalHeight() method, the layoutColumns() method iterates through the TextField objects, setting the height of each to the preferredHeight value. The layoutColumns() method then distributes just enough lines of text to each field so that no scrolling occurs in any individual field, and the text in each successive field begins where the text in the previous field ended. If the text alignment style has been set to justify then the justifyLastLine() method is called to justify the final line of text in a field. Otherwise that last line would be treated as an end-of-paragraph line and not justified.

Chapter 19: Working with bitmaps
In addition to its vector drawing capabilities, ActionScript 3.0 includes the ability to create bitmap images or manipulate the pixel data of external bitmap images that are loaded into a SWF. With the ability to access and change individual pixel values, you can create your own filter-like image effects and use the built-in noise functions to create textures and random noise. All of these techniques are described in this chapter.
Basics of working with bitmaps. 377 The Bitmap and BitmapData classes. 379 Manipulating pixels. 380 Copying bitmap data. 383 Making textures with noise functions. 384 Scrolling bitmaps. 386 Taking advantage of mipmapping. 386 Example: Animated spinning moon. 387
Basics of working with bitmaps
Introduction to working with bitmaps
When you work with digital images, youre likely to encounter two main types of graphics: bitmap and vector. Bitmap graphics, also known as raster graphics, are composed of tiny squares (pixels) that are arranged in a rectangular grid formation. Vector graphics are composed of mathematically generated geometric shapes such as lines, curves, and polygons. Bitmap images are defined by the width and height of the image, measured in pixels, and the number of bits contained in each pixel, which represents the number of colors a pixel can contain. In the case of a bitmap image that utilizes the RGB color model, the pixels are made up of three bytes: red, green, and blue. Each of these bytes contains a value ranging from 0 to 255. When the bytes are combined within the pixel, they produce a color similar to an artist mixing paint colors. For example, a pixel containing byte values of red-255, green-102 and blue-0 would produce a vibrant orange color. The quality of a bitmap image is determined by combining the resolution of the image with its color depth bit value. Resolution relates to the number of pixels contained within an image. The greater the number of pixels, the higher the resolution and the finer the image appears. Color depth relates to the amount of information a pixel can contain. For example, an image that has a color depth value of 16 bits per pixel cannot represent the same number of colors as an image that has a color depth of 48 bits. As a result, the 48-bit image will have smoother degrees of shading than its 16-bit counterpart. Because bitmap graphics are resolution-dependent, they dont scale very well. This is most noticeable when bitmap images are scaled up in size. Scaling up a bitmap usually results in a loss of detail and quality.

The following example creates a 150 x 150 pixel BitmapData object that calls the perlinNoise() method to generate a green and blue cloud effect:
import flash.display.Bitmap; import flash.display.BitmapData; var myBitmapDataObject:BitmapData = new BitmapData(150, 150, false, 0x00FF0000); var seed:Number = Math.floor(Math.random() * 100); var channels:uint = BitmapDataChannel.GREEN | BitmapDataChannel.BLUE myBitmapDataObject.perlinNoise(100, 80, 6, seed, false, true, channels, false, null); var myBitmap:Bitmap = new Bitmap(myBitmapDataObject); addChild(myBitmap);

ADOBE FLEX 3 386

Scrolling bitmaps
Imagine you have created a street mapping application where each time the user moves the map you are required to update the view (even if the map has been moved by just a few pixels). One way to create this functionality would be to re-render a new image containing the updated map view each time the user moves the map. Alternatively, you could create a large single image and the scroll() method. The scroll() method copies an on-screen bitmap and then pastes it to a new offset locationspecified by (x, y) parameters. If a portion of the bitmap happens to reside off-stage, this gives the effect that the image has shifted. When combined with a timer function (or an enterFrame event), you can make the image appear to be animating or scrolling. The following example takes the previous perlin noise example and generates a larger bitmap image (three-fourths of which is rendered off-stage). The scroll() method is then applied, along with an enterFrame event listener that offsets the image by one pixel in a diagonally downward direction. This method is called each time the frame is entered and as a result, the offscreen portions of the image are rendered to the Stage as the image scrolls down.
import flash.display.Bitmap; import flash.display.BitmapData; var myBitmapDataObject:BitmapData = new BitmapData(1000, 1000, false, 0x00FF0000); var seed:Number = Math.floor(Math.random() * 100); var channels:uint = BitmapDataChannel.GREEN | BitmapDataChannel.BLUE; myBitmapDataObject.perlinNoise(100, 80, 6, seed, false, true, channels, false, null); var myBitmap:Bitmap = new Bitmap(myBitmapDataObject); myBitmap.x = -750; myBitmap.y = -750; addChild(myBitmap); addEventListener(Event.ENTER_FRAME, scrollBitmap); function scrollBitmap(event:Event):void { myBitmapDataObject.scroll(1, 1); }

var cam:Camera = Camera.getCamera(); if (cam != null) { var vid:Video = new Video(); vid.attachCamera(cam); addChild(vid); }
Detecting permissions for camera access
Before the cameras output can be displayed, the user must explicitly allow Flash Player to access the camera. When the attachCamera() method gets called Flash Player displays the Flash Player Settings dialog box which prompts the user to either allow or deny Flash Player access to the camera and microphone. If the user clicked the Allow button, the cameras output is displayed in the Video instance on the Stage. If the user clicked the Deny button, Flash Player is unable to connect to the camera and the Video object will not display anything.

ADOBE FLEX 3 414

If the user does not have a camera installed, Flash Player will display nothing. If the user does have a camera installed, Flash Player will display the Flash Player Settings dialog which prompts the user to either allow or deny Flash Player to access the Camera. If the user allows access to their camera the video will be displayed back to the user, otherwise nothing will be displayed. If you want to detect whether the user allowed or denied access to the camera, you can listen for the cameras status event (StatusEvent.STATUS), as seen in the following code:
var cam:Camera = Camera.getCamera(); if (cam != null) { cam.addEventListener(StatusEvent.STATUS, statusHandler); var vid:Video = new Video(); vid.attachCamera(cam); addChild(vid); } function statusHandler(event:StatusEvent):void { // This event gets dispatched when the user clicks the "Allow" or "Deny" // button in the Flash Player Settings dialog box. trace(event.code); // "Camera.Muted" or "Camera.Unmuted" }
The statusHandler() function gets called as soon as the user clicks either Allow or Deny. You can detect which button the user clicked, using one of two methods:
The event parameter of the statusHandler() function contains a code property which contains the string Camera.Muted or Camera.Unmuted. If the value is Camera.Muted the user clicked the Deny button and Flash Player is unable to access the camera. You can see an example of this in the following snippet:
function statusHandler(event:StatusEvent):void { switch (event.code) { case "Camera.Muted": trace("User clicked Deny."); break; case "Camera.Unmuted": trace("User clicked Accept."); break; } }
The Camera class contains a read-only property named muted which specifies whether the user has denied access to the camera (true) or allowed access (false) in the Flash Player Privacy panel. You can see an example of this in the following snippet:
function statusHandler(event:StatusEvent):void { if (cam.muted) { trace("User clicked Deny."); } else { trace("User clicked Accept."); } }

Common tasks for working with sound
This chapter describes the following sound-related tasks that you will likely want to perform:
Loading external mp3 files and tracking their loading progress Playing, pausing, resuming, and stopping sounds Playing streaming sounds while they are being loaded Manipulating sound volume and panning Retrieving ID3 metadata from an mp3 file Using raw sound wave data Capturing and replaying sound input from a users microphone
Amplitude: The distance of a point on the sound waveform from the zero or equilibrium line.
Bit rate: The amount of data that is encoded or streamed for each second of a sound file. For mp3 files, the bit rate is usually stated in terms of thousands of bits per second (kbps). A higher bit rate generally means a higher quality sound wave.
Buffering: The receiving and storing of sound data before it is played back. mp3: MPEG-1 Audio Layer 3, or mp3, is a popular sound compression format. Panning: The positioning of an audio signal between the left and right channels in a stereo soundfield. Peak: The highest point in a waveform.
Sampling rate: Defines the number of samples per second taken from an analog audio signal to make a digital signal. The sampling rate of standard compact disc audio is 44.1 kHz or 44,100 samples per second. Streaming: The process of playing the early portions of a sound file or video file while later portions of that file are still being loaded from a server.

ADOBE FLEX 3 426

Volume: The loudness of a sound. Waveform: The shape of a graph of the varying amplitudes of a sound signal over time.
Understanding the sound architecture
Your applications can load sound data from four main sources:
External sound files loaded at run time Sound resources embedded within the applications SWF file Sound data from a microphone attached to the users system Sound data streamed from a remote media server, such as Flash Media Server
Sound data can be fully loaded before it is played back, or it can be streamed, meaning that it is played back while it is still loading. ActionScript 3.0, Flash Player, and AIR support sound files that are stored in the mp3 format. They cannot directly load or play sound files in other formats like WAV or AIFF. The ActionScript 3.0 sound architecture makes use of the following classes in the flash.media package.

If the remote document contains name-value pairs, you can parse the data using the URLVariables class by passing in the contents of the loaded file, as follows:
private function completeHandler(event:Event):void { var loader2:URLLoader = URLLoader(event.target); var variables:URLVariables = new URLVariables(loader2.data); trace(variables.dayNames); }
Each name-value pair from the external file is created as a property in the URLVariables object. Each property within the variables object in the previous code sample is treated as a string. If the value of the name-value pair is a list of items, you can convert the string into an array by calling the String.split() method, as follows:
var dayNameArray:Array = variables.dayNames.split(",");

ADOBE FLEX 3 465

If you are loading numeric data from external text files, you need to convert the values into numeric values by using a top-level function, such as int(), uint(), or Number(). Instead of loading the contents of the remote file as a string and creating a new URLVariables object, you could instead set the URLLoader.dataFormat property to one of the static properties found in the URLLoaderDataFormat class. The three possible values for the URLLoader.dataFormat property are as follows:
URLLoaderDataFormat.BINARYThe URLLoader.data property will contain binary data stored in a

ByteArray object.

URLLoaderDataFormat.TEXTThe URLLoader.data property will contain text in a String object. URLLoaderDataFormat.VARIABLESThe URLLoader.data property will contain URL-encoded variables
stored in a URLVariables object. The following code demonstrates how setting the URLLoader.dataFormat property to URLLoaderDataFormat.VARIABLES allows you to automatically parse loaded data into a URLVariables object:
package { import import import import import
flash.display.Sprite; flash.events.*; flash.net.URLLoader; flash.net.URLLoaderDataFormat; flash.net.URLRequest;
public class URLLoaderDataFormatExample extends Sprite { public function URLLoaderDataFormatExample() { var request:URLRequest = new URLRequest("http://www.[yourdomain].com/params.txt"); var variables:URLLoader = new URLLoader(); variables.dataFormat = URLLoaderDataFormat.VARIABLES; variables.addEventListener(Event.COMPLETE, completeHandler); try { variables.load(request); } catch (error:Error) { trace("Unable to load URL: " + error); } } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); trace(loader.data.dayNames); } } }

<cross-domain-policy> <allow-access-from domain="*" to-ports="507" /> <allow-access-from domain="*.example.com" to-ports="507,516" /> <allow-access-from domain="*.example2.com" to-ports="516-523" /> <allow-access-from domain="www.example2.com" to-ports="507,516-523" /> <allow-access-from domain="www.example3.com" to-ports="*" /> </cross-domain-policy>
When policy files were first introduced in Flash Player 6, there was no support for socket policy files. Connections to socket servers were authorized by a policy file from the default location of the cross-domain policy file on an HTTP server on port 80 of the same host as the socket server. To make it possible to preserve existing server arrangements, Flash Player 9 still supports this capability. However, Flash Players default is now to retrieve a socket policy file on the same port as the socket connection. If you wish to use an HTTP-based policy file to authorize a socket connection, you must explicitly request the HTTP policy file using code such as the following:
Security.loadPolicyFile("http://socketServerHost.com/crossdomain.xml")
In addition, in order to authorize socket connections, an HTTP policy file must come only from the default location of the cross-domain policy file, and not from any other HTTP location. A policy file obtained from an HTTP server implicitly authorizes socket access to all ports 1024 and above; any to-ports attributes in an HTTP policy file are ignored. For more information on socket policy files, see Connecting to sockets on page 555.

Preloading policy files

Loading data from a server or connecting to a socket is an asynchronous operation, and Flash Player simply waits for the cross-domain policy file to finish downloading before it begins the main operation. However, extracting pixel data from images or extracting sample data from sounds is a synchronous operationthe cross-domain policy file must load before you can extract data. When you load the media, you need to specify that it check for a cross-domain policy file:

doc1

Boolean data type

The Boolean data type comprises two values: true and false. No other values are valid for variables of Boolean type. The default value of a Boolean variable that has been declared but not initialized is false.
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 57

int data type

The int data type is stored internally as a 32-bit integer and comprises the set of integers from -2,147,483,648 (-231) to 2,147,483,647 (231 - 1), inclusive. Previous versions of ActionScript offered only the Number data type, which was used for both integers and floating-point numbers. In ActionScript 3.0, you now have access to low-level machine types for 32-bit signed and unsigned integers. If your variable will not use floating-point numbers, using the int data type instead of the Number data type should be faster and more efficient. For integer values outside the range of the minimum and maximum int values, use the Number data type, which can handle values between positive and negative 9,007,199,254,740,992 (53-bit integer values). The default value for variables that are of the data type int is 0.

Null data type

The Null data type contains only one value, null. This is the default value for the String data type and all classes that define complex data types, including the Object class. None of the other primitive data types, such as Boolean, Number, int and uint, contain the value null. Flash Player and Adobe AIR will convert the value null to the appropriate default value if you attempt to assign null to variables of type Boolean, Number, int, or uint. You cannot use this data type as a type annotation.

Number data type

In ActionScript 3.0, the Number data type can represent integers, unsigned integers, and floating-point numbers. However, to maximize performance, you should use the Number data type only for integer values larger than the 32bit int and uint types can store or for floating-point numbers. To store a floating-point number, include a decimal point in the number. If you omit a decimal point, the number will be stored as an integer. The Number data type uses the 64-bit double-precision format as specified by the IEEE Standard for Binary FloatingPoint Arithmetic (IEEE-754). This standard dictates how floating-point numbers are stored using the 64 available bits. One bit is used to designate whether the number is positive or negative. Eleven bits are used for the exponent, which is stored as base 2. The remaining 52 bits are used to store the significand (also called the mantissa), which is the number that is raised to the power indicated by the exponent. By using some of its bits to store an exponent, the Number data type can store floating-point numbers significantly larger than if it used all of its bits for the significand. For example, if the Number data type used all 64 bits to store the significand, it could store a number as large as 265 - 1. By using 11 bits to store an exponent, the Number data type can raise its significand to a power of 21023. The maximum and minimum values that the Number type can represent are stored in static properties of the Number class called Number.MAX_VALUE and Number.MIN_VALUE.

In ActionScript 3.0, an attempt to access a private property using the dot operator (myExample.privVar) results in a compile-time error if you are using strict mode. Otherwise, the error is reported at run time, just as it is when you use the property access operator (myExample["privVar"]). The following table summarizes the results of attempting to access a private property that belongs to a sealed (not dynamic) class:
Strict mode dot operator (.) bracket operator ([]) compile-time error run-time error Standard mode run-time error run-time error
In classes declared with the dynamic attribute, attempts to access a private variable will not result in a run-time error. Instead, the variable is simply not visible, so Flash Player or Adobe AIR returns the value undefined. A compiletime error occurs, however, if you use the dot operator in strict mode. The following example is the same as the previous example, except that the PrivateExample class is declared as a dynamic class:
dynamic class PrivateExample { private var privVar:String = "private variable"; } var myExample:PrivateExample = new PrivateExample(); trace(myExample.privVar);// compile-time error in strict mode trace(myExample["privVar"]); // output: undefined
Dynamic classes generally return the value undefined instead of generating an error when code external to a class attempts to access a private property. The following table shows that an error is generated only when the dot operator is used to access a private property in strict mode:
Strict mode dot operator (.) bracket operator ([]) compile-time error

Standard mode

undefined undefined
The protected attribute, which is new for ActionScript 3.0, makes a property visible to callers within its own class or in a subclass. In other words, a protected property is available within its own class or to classes that lie anywhere below it in the inheritance hierarchy. This is true whether the subclass is in the same package or in a different package. For those familiar with ActionScript 2.0, this functionality is similar to the private attribute in ActionScript 2.0. The ActionScript 3.0 protected attribute is also similar to the protected attribute in Java, but differs in that the Java version also permits access to callers within the same package. The protected attribute is useful when you have a variable or method that your subclasses need but that you want to hide from code that is outside the inheritance chain.
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 96
The internal attribute, which is new for ActionScript 3.0, makes a property visible to callers within its own package. This is the default attribute for code inside a package, and it applies to any property that does not have any of the following attributes:

The second parameter of the split() method, which is optional, defines the maximum size of the array that is returned. You can also use a regular expression as the delimiter character:
var str:String = "Give me\t5." var a:Array = str.split(/\s+/); // a == ["Give","me","5."]
For more information, see Using regular expressions on page 203 and the ActionScript 3.0 Language and Components Reference.
Finding patterns in strings and replacing substrings
The String class includes the following methods for working with patterns in strings:
Use the match() and search() methods to locate substrings that match a pattern. Use the replace() method to find substrings that match a pattern and replace them with a specified substring.
These methods are described in the following sections. You can use strings or regular expressions to define patterns used in these methods. For more information on regular expressions, see Using regular expressions on page 203. Finding matching substrings The search() method returns the index position of the first substring that matches a given pattern, as shown in this example:
var str:String = "The more the merrier."; // (This search is case-sensitive.) trace(str.search("the")); // output: 9
You can also use regular expressions to define the pattern to match, as this example shows:
var pattern:RegExp = /the/i; var str:String = "The more the merrier."; trace(str.search(pattern)); // 0
The output of the trace() method is 0, because the first character in the string is index position 0. The i flag is set in the regular expression, so the search is not case-sensitive. The search() method finds only one match and returns its starting index position, even if the g (global) flag is set in the regular expression. The following example shows a more intricate regular expression, one that matches a string in double quotation marks:
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 146
var pattern:RegExp = /"[^"]*"/; var str:String = "The \"more\" the merrier."; trace(str.search(pattern)); // output: 4 str = "The \"more the merrier."; trace(str.search(pattern)); // output: -1 // (Indicates no match, since there is no closing double quotation mark.)

var rivers:Array = ["Nile", "Amazon", "Yangtze", "Mississippi"]; var riverCSV:String = rivers.toString(); trace(riverCSV); // output: Nile,Amazon,Yangtze,Mississippi var riverPSV:String = rivers.join("+"); trace(riverPSV); // output: Nile+Amazon+Yangtze+Mississippi
One issue to be aware of with the join() method is that any nested Array or Vector instances are always returned with comma-separated values, no matter what separator you specify for the main array elements, as the following example shows:
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 165
var nested:Array = ["b","c","d"]; var letters:Array = ["a",nested,"e"]; var joined:String = letters.join("+"); trace(joined); // output: a+b,c,d+e

Associative arrays

An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value. An associative array is an instance of the Object class, which means that each key corresponds to a property name. Associative arrays are unordered collections of key and value pairs. Your code should not expect the keys of an associative array to be in a specific order. ActionScript 3.0 also includes an advanced type of associative array called a dictionary. Dictionaries, which are instances of the Dictionary class in the flash.utils package, use keys that can be of any data type. In other words, dictionary keys are not limited to values of type String.
Associative arrays with string keys
There are two ways to create associative arrays in ActionScript 3.0. The first way is to use an Object instance. By using an Object instance you can initialize your array with an object literal. An instance of the Object class, also called a generic object, is functionally identical to an associative array. Each property name of the generic object serves as the key that provides access to a stored value. The following example creates an associative array named monitorInfo, using an object literal to initialize the array with two key and value pairs:
var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"}; trace(monitorInfo["type"], monitorInfo["resolution"]); // output: Flat Panel 1600 x 1200
If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array, as follows:

import flash.display.Sprite; import flash.utils.Dictionary; var groupMap:Dictionary = new Dictionary(); // objects to use var spr1:Sprite = var spr2:Sprite = var spr3:Sprite = as keys new Sprite(); new Sprite(); new Sprite();
// objects to use as values var groupA:Object = new Object(); var groupB:Object = new Object(); // Create new key-value pairs in dictionary. groupMap[spr1] = groupA; groupMap[spr2] = groupB; groupMap[spr3] = groupB; if (groupMap[spr1] { trace("spr1 is } if (groupMap[spr2] { trace("spr2 is } if (groupMap[spr3] { trace("spr3 is } == groupA) in groupA"); == groupB) in groupB"); == groupB) in groupB");
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 167
Iterating with object keys You can iterate through the contents of a Dictionary object with either a for.in loop or a for each.in loop. A for.in loop allows you to iterate based on the keys, whereas a for each.in loop allows you to iterate based on the values associated with each key. Use the for.in loop for direct access to the object keys of a Dictionary object. You can also access the values of the Dictionary object with the array access ([]) operator. The following code uses the previous example of the groupMap dictionary to show how to iterate through a Dictionary object with the for.in loop:
for (var key:Object in groupMap) { trace(key, groupMap[key]); } /* output: [object Sprite] [object Object] [object Sprite] [object Object] [object Sprite] [object Object] */
Use the for each.in loop for direct access to the values of a Dictionary object. The following code also uses the groupMap dictionary to show how to iterate through a Dictionary object with the for each.in loop:
for each (var item:Object in groupMap) { trace(item); } /* output: [object Object] [object Object] [object Object] */
Object keys and memory management Adobe Flash Player and Adobe AIR use a garbage collection system to recover memory that is no longer used. When an object has no references pointing to it, the object becomes eligible for garbage collection, and the memory is recovered the next time the garbage collection system executes. For example, the following code creates a new object and assigns a reference to the object to the variable myObject:

Defining winding rules

Flash Player 10 and Adobe AIR 1.5 also introduce the concept of path winding: the direction for a path. The winding for a path is either positive (clockwise) or negative (counter-clockwise). The order in which the renderer interprets the coordinates provided by the vector for the data parameter determines the winding.
Positive and negative winding A. Arrows indicate drawing direction B. Positively wound (clockwise) C. Negatively wound (counter-clockwise)
Additionally, notice that the Graphics.drawPath() method has an optional third parameter called winding:
drawPath(commands:Vector.<int>, data:Vector.<Number>, winding:String = "evenOdd"):void
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 330
In this context, the third parameter is a string or a constant that specifies the winding or fill rule for intersecting paths. (The constant values are defined in the GraphicsPathWinding class as GraphicsPathWinding.EVEN_ODD or GraphicsPathWinding.NON_ZERO.) The winding rule is important when paths intersect. The even-odd rule is the standard winding rule and is the rule used by the legacy drawing API. The Even-odd rule is also the default rule for the Graphics.drawPath() method. With the even-odd winding rule, any intersecting paths alternate between open and closed fills. If two squares drawn with the same fill intersect, the area in which the intersection occurs is filled. Generally, adjacent areas are neither both filled nor both unfilled. The non-zero rule, on the other hand, depends on winding (drawing direction) to determine whether areas defined by intersecting paths are filled. When paths of opposite winding intersect, the area defined is unfilled, much like with even-odd. For paths of the same winding, the area that would be unfilled is filled:
Winding rules for intersecting areas A. Even-odd winding rule B. Non-zero winding rule

Winding rule names

The names refer to a more specific rule that defines how these fills are managed. Positively wound paths are assigned a value of +1; negatively wound paths are assigned a value of -1. Starting from a point within an enclosed area of a shape, draw a line from that point extending out indefinitely. The number of times that line crosses a path, and the combined values of those paths, are used to determine the fill. For even-odd winding, the count of times the line crosses a path is used. When the count is odd, the area is filled. For even counts, the area is unfilled. For non-zero winding, the values assigned to the paths are used. When the combined values of the path are not 0, the area is filled. When the combined value is 0, the area is unfilled.

The first six filters are simple filters that can be used to create one specific effect, with some customization of the effect available. Those six filters can be applied using ActionScript, and can also be applied to objects in Adobe Flash CS4 Professional using the Filters panel. Consequently, even if youre applying filters using ActionScript, if you have the Flash authoring tool you can use the visual interface to quickly try out different filters and settings to figure out how to create a desired effect.
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 354
The final four filters are available in ActionScript only. Those filters, the color matrix filter, convolution filter, displacement map filter, and shader filter, are much more flexible in the types of effects that they can be used to create. Rather than being optimized for a single effect, they provide power and flexibility. For example, by selecting different values for its matrix, the convolution filter can be used to create effects such as blurring, embossing, sharpening, finding color edges, transformations, and more. Each of the filters, whether simple or complex, can be customized using their properties. Generally, you have two choices for setting filter properties. All the filters let you set the properties by passing parameter values to the filter objects constructor. Alternatively, whether or not you set the filter properties by passing parameters, you can adjust the filters later by setting values for the filter objects properties. Most of the example code listings set the properties directly, in order to make the example easier to follow. Nevertheless, you could usually achieve the same result in fewer lines of code by passing the values as parameters in the filter objects constructor. For more details on the specifics of each filter, its properties and its constructor parameters, see the listings for the flash.filters package in the ActionScript 3.0 Language and Components Reference.

Bevel filter

The BevelFilter class allows you to add a 3D beveled edge to the filtered object. This filter makes the hard corners or edges of your object look like they have been chiseled, or beveled, away. The BevelFilter class properties allow you to customize the appearance of the bevel. You can set highlight and shadow colors, bevel edge blurs, bevel angles, and bevel edge placement; you can even create a knockout effect. The following example loads an external image and applies a bevel filter to it.
import import import import import flash.display.*; flash.filters.BevelFilter; flash.filters.BitmapFilterQuality; flash.filters.BitmapFilterType; flash.net.URLRequest;

First, when the method is called it receives a parameter, radius, indicating the radius of the circle-shaped image to create. Next, the code creates the BitmapData object on which the circle will be drawn. That object, named result, is eventually passed back as the return value of the method. As shown in the following code snippet, the result BitmapData instance is created with a width and height as big as the diameter of the circle, without transparency (false for the third parameter), and pre-filled with the color 0x808080 (middle gray):
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 493
var result:BitmapData = new BitmapData(diameter, diameter, false, 0x808080);
Next, the code uses two loops to iterate over each pixel of the image. The outer loop goes through each column of the image from left to right (using the variable i to represent the horizontal position of the pixel currently being manipulated), while the inner loop goes through each pixel of the current column from top to bottom (with the variable j representing the vertical position of the current pixel). The code for the loops (with the inner loops contents omitted) is shown here:
for (var i:int = 0; i < diameter; i++) { for (var j:int = 0; j < diameter; j++) {. } }
As the loops cycle through the pixels one by one, at each pixel a value (the color value of that pixel in the map image) is calculated. This process involves four steps:
1 The code calculates the distance of the current pixel from the center of the circle along the x axis (i - radius).
That value is divided by the radius to make it a percentage of the radius rather than an absolute distance ((i radius) / radius). That percentage value is stored in a variable named pctX, and the equivalent value for the y axis is calculated and stored in the variable pctY, as shown in this code:
var pctX:Number = (i - radius) / radius; var pctY:Number = (j - radius) / radius;
2 Using a standard trigonometric formula, the Pythagorean theorem, the linear distance between the center of the
circle and the current point is calculated from pctX and pctY. That value is stored in a variable named pctDistance, as shown here:
var pctDistance:Number = Math.sqrt(pctX * pctX + pctY * pctY);
3 Next, the code checks whether the distance percentage is less than 1 (meaning 100% of the radius, or in other words,
if the pixel being considered is within the radius of the cicle). If the pixel falls inside the circle, it is assigned a calculated color value (omitted here, but described in step 4); if not, nothing further happens with that pixel so its color is left as the default middle gray:
if (pctDistance < 1) {. }
4 For those pixels that fall inside the circle, a color value is calculated for the pixel. The final color will be a shade of
red ranging from black (0% red) at the left edge of the circle to bright (100%) red at the right edge of the circle. The color value is initially calculated in three parts (red, green, and blue), as shown here:

Detecting the end of a video stream
In order to listen for the beginning and end of a video stream, you need to add an event listener to the NetStream instance to listen for the netStatus event. The following code demonstrates how to listen for the various codes throughout the videos playback:
ns.addEventListener(NetStatusEvent.NET_STATUS, statusHandler); function statusHandler(event:NetStatusEvent):void { trace(event.info.code) }
The previous code generates the following output:
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 522
NetStream.Play.Start NetStream.Buffer.Empty NetStream.Buffer.Full NetStream.Buffer.Empty NetStream.Buffer.Full NetStream.Buffer.Empty NetStream.Buffer.Full NetStream.Buffer.Flush NetStream.Play.Stop NetStream.Buffer.Empty NetStream.Buffer.Flush
The two codes that you want to specifically listen for are NetStream.Play.Start and NetStream.Play.Stop which signal the beginning and end of the videos playback. The following snippet uses a switch statement to filter these two codes and trace a message:
function statusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetStream.Play.Start": trace("Start [" + ns.time.toFixed(3) + " seconds]"); break; case "NetStream.Play.Stop": trace("Stop [" + ns.time.toFixed(3) + " seconds]"); break; } }
By listening for the netStatus event (NetStatusEvent.NET_STATUS), you can build a video player which loads the next video in a playlist once the current video has finished playing.
Playing video in full-screen mode
Flash Player and AIR allow you to create a full-screen application for your video playback, and support scaling video to full screen. For AIR content running in full-screen mode, the system screen saver and power-saving options are disabled during play until either the video input stops or the user exits full-screen mode. For full details on using full-screen mode, see Working with full-screen mode on page 280. Enabling full-screen mode for Flash Player in a browser Before you can implement full-screen mode for Flash Player in a browser, enable it through the Publish template for your application. Templates that allow full screen include <object> and <embed> tags that contain an allowFullScreen parameter. The following example shows the allowFullScreen parameter in an <embed> tag.

Loading an external video playlist file
The external playlist.xml file specifies which videos to load, and the order to play them back in. In order to load the XML file, you need to use a URLLoader object and a URLRequest object, as seen in the following code:
uldr = new URLLoader(); uldr.addEventListener(Event.COMPLETE, xmlCompleteHandler); uldr.load(new URLRequest(PLAYLIST_XML_URL));
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 549
This code is placed in the VideoJukebox classs constructor so the file is loaded before any other code is run. As soon as the XML file has finished loading, the xmlCompleteHandler() method is called which parses the external file into an XML object, as seen in the following code:
private function xmlCompleteHandler(event:Event):void { playlist = XML(event.target.data); videosXML = playlist.video; main(); }
The playlist XML object contains the raw XML from the external file, whereas the videosXML is an XMLList object which contains just the video nodes. A sample playlist.xml file can be seen in the following snippet:
<videos> <video url="video/caption_video.flv" /> <video url="video/cuepoints.flv" /> <video url="video/water.flv" /> </videos>
Finally, the xmlCompleteHandler() method calls the main() method which sets up the various component instances on the display list, as well as the NetConnection and NetStream objects which are used to load the external FLV files.
Creating the user interface
To build the user interface you need to drag five Button instances onto the display list and give them the following instance names: playButton, pauseButton, stopButton, backButton, and forwardButton. For each of these Button instances, youll need to assign a handler for the click event, as seen in the following snippet:
playButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); pauseButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); stopButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); backButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); forwardButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);
The buttonClickHandler() method uses a switch statement to determine which button instance was clicked, as seen in the following code:
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 550
private function buttonClickHandler(event:MouseEvent):void { switch (event.currentTarget) { case playButton: ns.resume(); break; case pauseButton: ns.togglePause(); break; case stopButton: ns.pause(); ns.seek(0); break; case backButton: playPreviousVideo(); break; case forwardButton: playNextVideo(); break; } }
Next, add a Slider instance to the display list and give it an instance name of volumeSlider. The following code sets the slider instances liveDragging property to true and defines an event listener for the slider instances change event:

PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 555

Working with sound

Common tasks for working with sound
This chapter describes the following sound-related tasks that you will likely want to perform:
Loading external mp3 files and tracking their loading progress Playing, pausing, resuming, and stopping sounds Playing streaming sounds while they are being loaded Manipulating sound volume and panning Retrieving ID3 metadata from an mp3 file Using raw sound wave data Dynamically generating sound Capturing and replaying sound input from a users microphone
Amplitude: The distance of a point on the sound waveform from the zero or equilibrium line. Bit rate: The amount of data that is encoded or streamed for each second of a sound file. For mp3 files, the bit rate is usually stated in terms of thousands of bits per second (kbps). A higher bit rate generally means a higher quality sound wave. Buffering: The receiving and storing of sound data before it is played back. mp3: MPEG-1 Audio Layer 3, or mp3, is a popular sound compression format. Panning: The positioning of an audio signal between the left and right channels in a stereo soundfield. Peak: The highest point in a waveform. Sampling rate: Defines the number of samples per second taken from an analog audio signal to make a digital signal. The sampling rate of standard compact disc audio is 44.1 kHz or 44,100 samples per second. Streaming: The process of playing the early portions of a sound file or video file while later portions of that file are still being loaded from a server. Volume: The loudness of a sound. Waveform: The shape of a graph of the varying amplitudes of a sound signal over time.
As youre working through this chapter, you may want to try out some of the example code listings. Since this chapter covers working with sound in ActionScript, many of the examples do something that involves working with a sound filemaking it play, stopping playback, or adjusting the sound in some way. To test the examples in this chapter:
1 Create a new Flash document and save it on your computer. 2 In the Timeline, select the first keyframe and open the Actions panel. 3 Copy the example code listing into the Script pane. 4 If the code involves loading an external sound file, it will have a line of code that looks something like this:
var req:URLRequest = new URLRequest("click.mp3"); var s:Sound = new Sound(req); s.play();
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 556
where click.mp3 is the name of the sound file being loaded. In order to test these examples, youll need to have an mp3 file to use. You should put the mp3 file in the same folder as your Flash document. You should then alter the code to use the name of your mp3 file instead of the name in the code listing (for example, in the code above youd change click.mp3 to the name of your mp3 file).

PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 563
Limitations on generated sounds
When you use a sampleData event listener with a Sound object, the only other Sound methods that are enabled are Sound.extract() and Sound.play(). Calling any other methods or properties results in an exception. All methods and properties of the SoundChannel object are still enabled.

Playing sounds

Playing a loaded sound can be as simple as calling the Sound.play() method for a Sound object, as follows:
var snd:Sound = new Sound(new URLRequest("smallSound.mp3")); snd.play();
When playing back sounds using ActionScript 3.0, you can perform the following operations:
Play a sound from a specific starting position Pause a sound and resume playback from the same position later Know exactly when a sound finishes playing Track the playback progress of a sound Change volume or panning while a sound plays
To perform these operations during playback, use the SoundChannel, SoundMixer, and SoundTransform classes. The SoundChannel class controls the playback of a single sound. The SoundChannel.position property can be thought of as a playhead, indicating the current point in the sound data thats being played. When an application calls the Sound.play() method, a new instance of the SoundChannel class is created to control the playback. Your application can play a sound from a specific starting position by passing that position, in terms of milliseconds, as the startTime parameter of the Sound.play() method. It can also specify a fixed number of times to repeat the sound in rapid succession by passing a numeric value in the loops parameter of the Sound.play() method. When the Sound.play() method is called with both a startTime parameter and a loops parameter, the sound is played back repeatedly from the same starting point each time, as shown in the following code:
var snd:Sound = new Sound(new URLRequest("repeatingSound.mp3")); snd.play(1000, 3);
In this example, the sound is played from a point one second after the start of the sound, three times in succession.
Pausing and resuming a sound
If your application plays long sounds, like songs or podcasts, you probably want to let users pause and resume the playback of those sounds. A sound cannot literally be paused during playback in ActionScript; it can only be stopped. However, a sound can be played starting from any point. You can record the position of the sound at the time it was stopped, and then replay the sound starting at that position later. For example, lets say your code loads and plays a sound file like this:
var snd:Sound = new Sound(new URLRequest("bigSound.mp3")); var channel:SoundChannel = snd.play();
While the sound plays, the SoundChannel.position property indicates the point in the sound file that is currently being played. Your application can store the position value before stopping the sound from playing, as follows:

Working with IPv6 addresses
Flash Player 9.0.115.0 and later support IPv6 (Internet Protocol version 6). IPv6 is a version of Internet Protocol that supports 128-bit addresses (an improvement on the earlier IPv4 protocol that supports 32-bit addresses). You might need to activate IPv6 on your networking interfaces. For more information, see the Help for the operating system hosting the data. If IPv6 is supported on the hosting system, you can specify numeric IPv6 literal addresses in URLs enclosed in brackets ([]), as in the following:
rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]:1935/test
Flash Player returns literal IPv6 values, according to the following rules:
Flash Player returns the long form of the string for IPv6 addresses. The IP value has no double-colon abbreviations. Hexadecimal digits are lowercase only. IPv6 addresses are enclosed in square brackets ([]).
PROGRAMMING ACTIONSCRIPT 3.0 FOR FLASH 597
Each address quartet is output as 0 to 4 hexadecimal digits, with the leading zeros omitted. An address quartet of all zeros is output as a single zero (not a double colon) except as noted in the following list of exceptions.
The IPv6 values that Flash Player returns have the following exceptions:
An unspecified IPv6 address (all zeros) is output as [::]. The loopback or localhost IPv6 address is output as [::1]. IPv4 mapped (converted to IPv6) addresses are output as [::ffff:a.b.c.d], where a.b.c.d is a typical IPv4 dotteddecimal value. IPv4 compatible addresses are output as [::a.b.c.d], where a.b.c.d is a typical IPv4 dotted-decimal value.
While youre working through this chapter you might want to test the example code listings. Several of the code listings in the chapter load external data or perform some other type of communication; often these samples include trace() function calls, so the results of running the example are displayed in the Output panel. Other examples actually perform some function, such as uploading a file to a server. Testing those examples will involve interacting with the SWF and confirming that they perform the action they claim to perform. The code examples fall into two categories. Some of the example listings are written assuming the code is in a standalone script, such as attached to a keyframe in a Flash document. To test those examples:

 

Tags

MP3000 Neonumeric NM2 Review SG-3090 NWZ-E444 330GSM Abit AU10 SU-VX720 6 16V Plcsw30 BES860 LN32C530 TXL32G20E DES-3052 IP6220D PL-Z560 Jaguar SGH-T669 1911 F Navigator CFD-360 Plhr76 LG PC12 HVL-F36AM VP-MX20C Nokia 6080 Star Wars Log-LOG Sumlog AK640 Blaster-2003 Edition 483-0 VSX-520-K P1201 Edition Fd D Sable 2003 SA3045 Webcam 2200 CDA-7842R Monitor Refrigerator 27 277 287 5000M LX3950W F60860 DSC-F88 GT3 RS Edition Istds S1000 Sacred-underworld PD-H300 Mk3 Elura 65 Player 7900 GS 17PT1564 Assassin 48430 VSX5000 TX23U MV-700HR D1400 EZ-guide 250 Eazygo XSC Steam CT-A7 KF300 PR3000 Optura 400 Samsung S860 Exai8580 RMV-202 SDC-368 WL-114V2 CDR870 CX3650 MZ-NF810 21FB3AB SMX-F30 SP Maxima-1999 8450 Live CDP-C535 HL-6050DN DVP-FX810 Vert TR AXM898U TCM-459V L194WT-SF Program Reflexes MVH-8200BT NV-HV60 CMT-J100 GR-B247WVS MES-202 BAR998HGN 950IS Vento ECR 5000

 

manuel d'instructions, Guide de l'utilisateur | Manual de instrucciones, Instrucciones de uso | Bedienungsanleitung, Bedienungsanleitung | Manual de Instruções, guia do usuário | инструкция | návod na použitie, Užívateľská príručka, návod k použití | bruksanvisningen | instrukcja, podręcznik użytkownika | kullanım kılavuzu, Kullanım | kézikönyv, használati útmutató | manuale di istruzioni, istruzioni d'uso | handleiding, gebruikershandleiding

 

Sitemap

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101