| Package | flash.media | 
| Class | public class Sound | 
| Inheritance | Sound  EventDispatcher  Object | 
| Subclasses | SoundAsset | 
| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
In Flash Player 10 and later and AIR 1.5 and later, you can also use this 
  class to work with sound that is generated dynamically. 
  In this case, the Sound object uses the function you assign to a sampleData event handler to
  poll for sound data. The sound is played as it is retrieved from a ByteArray object that
  you populate with sound data. You can use Sound.extract() to extract sound data from a 
  Sound object,
  after which you can manipulate it before writing it back to the stream for playback.
To control sounds that are embedded in a SWF file, use the properties in the SoundMixer class.
Note: The ActionScript 3.0 Sound API differs from ActionScript 2.0. In ActionScript 3.0, you cannot take sound objects and arrange them in a hierarchy to control their properties.
When you use this class, consider the following security model:
- Loading and playing a sound is not allowed if the calling file is in a network sandbox and the sound file to be loaded is local.
- By default, loading and playing a sound is not allowed if the calling file is local and tries to load and play a remote sound. A user must grant explicit permission to allow this type of access.
- Certain operations dealing with sound are restricted. The data in a loaded sound cannot
  be accessed by a file in a different domain unless you implement a cross-domain policy file.
  Sound-related APIs that fall under this restriction are Sound.id3,SoundMixer.computeSpectrum(),SoundMixer.bufferTime, and theSoundTransformclass.
However, in Adobe AIR, content in the application security sandbox (content
  installed with the AIR application) are not restricted by these security limitations.
For more information related to security, see the Flash Player Developer Center Topic: Security.
More examples
Playing sounds
Controlling sound volume and panning
Working with sound metadata
Accessing raw sound data
Sound example: Podcast Player
Learn more
Understanding the sound architecture
Working with embedded sounds
Working with streaming sound files
Working with dynamically generated audio
Security considerations when loading and playing sounds
Related API Elements
| Property | Defined By | ||
|---|---|---|---|
| bytesLoaded : uint [read-only] 
     Returns the currently available number of bytes in this sound object. | Sound | ||
| bytesTotal : int [read-only] 
     Returns the total number of bytes in this sound object. | Sound | ||
|  | constructor : Object 
	 A reference to the class object or constructor function for a given object instance. | Object | |
| id3 : ID3Info [read-only] 
     Provides access to the metadata that is part of an MP3 file. | Sound | ||
| isBuffering : Boolean [read-only] 
     Returns the buffering state of external MP3 files. | Sound | ||
| isURLInaccessible : Boolean [read-only] 
	 Indicates if the Sound.url property has been
	 truncated. | Sound | ||
| length : Number [read-only] 
     The length of the current sound in milliseconds. | Sound | ||
| url : String [read-only] 
     The URL from which this sound was loaded. | Sound | ||
| Method | Defined By | ||
|---|---|---|---|
| 
     Creates a new Sound object. | Sound | ||
|  | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void 
	Registers an event listener object with an EventDispatcher object so that the listener 
	receives notification of an event. | EventDispatcher | |
| 
     Closes the stream, causing any download of data to cease. | Sound | ||
|  | 
	Dispatches an event into the event flow. | EventDispatcher | |
| 
      Extracts raw sound data from a Sound object. | Sound | ||
|  | 
	Checks whether the EventDispatcher object has any listeners registered for a specific type 
	of event. | EventDispatcher | |
|  | 
	 Indicates whether an object has a specified property defined. | Object | |
|  | 
	 Indicates whether an instance of the Object class is in the prototype chain of the object specified 
	 as the parameter. | Object | |
| 
     Initiates loading of an external MP3 file from the specified URL. | Sound | ||
| 
	 load MP3 sound data from a ByteArray object into a Sound object. | Sound | ||
| loadPCMFromByteArray(bytes:ByteArray, samples:uint, format:String = "float", stereo:Boolean = true, sampleRate:Number = 44100.0):void 
	 Load PCM 32-bit floating point sound data from a ByteArray object into a Sound object. | Sound | ||
| play(startTime:Number = 0, loops:int = 0, sndTransform:flash.media:SoundTransform = null):SoundChannel 
     Generates a new SoundChannel object to play back the sound. | Sound | ||
|  | 
	 Indicates whether the specified property exists and is enumerable. | Object | |
|  | 
	Removes a listener from the EventDispatcher object. | EventDispatcher | |
|  | 
     Sets the availability of a dynamic property for loop operations. | Object | |
|  | 
	 Returns the string representation of this object, formatted according to locale-specific conventions. | Object | |
|  | 
	 Returns the string representation of the specified object. | Object | |
|  | 
	 Returns the primitive value of the specified object. | Object | |
|  | 
	Checks whether an event listener is registered with this EventDispatcher object or any of 
	its ancestors for the specified event type. | EventDispatcher | |
| Event | Summary | Defined By | ||
|---|---|---|---|---|
|  | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher | ||
| Dispatched when data has loaded successfully. | Sound | |||
|  | [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive. | EventDispatcher | ||
| Dispatched by a Sound object when ID3 data is available for an MP3 sound. | Sound | |||
| Dispatched when an input/output error occurs that causes a load operation to fail. | Sound | |||
| Dispatched when a load operation starts. | Sound | |||
| Dispatched when data is received as a load operation progresses. | Sound | |||
| Dispatched when the runtime requests new audio data. | Sound | |||
| bytesLoaded | property | 
bytesLoaded:uint  [read-only] | Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Returns the currently available number of bytes in this sound object. This property is usually useful only for externally loaded files.
Implementation
    public function get bytesLoaded():uint| bytesTotal | property | 
| id3 | property | 
id3:ID3Info  [read-only] | Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Provides access to the metadata that is part of an MP3 file.
MP3 sound files can contain ID3 tags, which provide metadata about the 
     file. If an MP3 sound that you load using the Sound.load() 
     method contains ID3 tags, you can query these properties. Only ID3 tags 
     that use the UTF-8 character set are supported.
Flash Player 9 and later and AIR support 
      ID3 2.0 tags, 
     specifically 2.3 and 2.4. The following tables list the standard ID3 2.0 tags 
     and the type of content the tags represent. The Sound.id3 property provides
     access to these tags through the format 
     my_sound.id3.COMM, my_sound.id3.TIME, and so on. The first
     table describes tags that can be accessed either through the ID3 2.0 property name or
     the ActionScript property name. The second table describes ID3 tags that are supported but do not have
     predefined properties in ActionScript. 
| ID3 2.0 tag | Corresponding Sound class property | 
| COMM | Sound.id3.comment | 
| TALB | Sound.id3.album | 
| TCON | Sound.id3.genre | 
| TIT2 | Sound.id3.songName | 
| TPE1 | Sound.id3.artist | 
| TRCK | Sound.id3.track | 
| TYER | Sound.id3.year | 
The following table describes ID3 tags that are supported but do not have
     predefined properties in the Sound class. You access them by calling 
     mySound.id3.TFLT, mySound.id3.TIME, and so on. NOTE: None of
     these tags are supported in Flash Lite 4.
| Property | Description | 
| TFLT | File type | 
| TIME | Time | 
| TIT1 | Content group description | 
| TIT2 | Title/song name/content description | 
| TIT3 | Subtitle/description refinement | 
| TKEY | Initial key | 
| TLAN | Languages | 
| TLEN | Length | 
| TMED | Media type | 
| TOAL | Original album/movie/show title | 
| TOFN | Original filename | 
| TOLY | Original lyricists/text writers | 
| TOPE | Original artists/performers | 
| TORY | Original release year | 
| TOWN | File owner/licensee | 
| TPE1 | Lead performers/soloists | 
| TPE2 | Band/orchestra/accompaniment | 
| TPE3 | Conductor/performer refinement | 
| TPE4 | Interpreted, remixed, or otherwise modified by | 
| TPOS | Part of a set | 
| TPUB | Publisher | 
| TRCK | Track number/position in set | 
| TRDA | Recording dates | 
| TRSN | Internet radio station name | 
| TRSO | Internet radio station owner | 
| TSIZ | Size | 
| TSRC | ISRC (international standard recording code) | 
| TSSE | Software/hardware and settings used for encoding | 
| TYER | Year | 
| WXXX | URL link frame | 
When using this property, consider the Flash Player security model:
- The id3property of a Sound object is always permitted for SWF files that are in the same security sandbox as the sound file. For files in other sandboxes, there are security checks.
- When you load the sound, using the load()method of the Sound class, you can specify acontextparameter, which is a SoundLoaderContext object. If you set thecheckPolicyFileproperty of the SoundLoaderContext object totrue, Flash Player checks for a URL policy file on the server from which the sound is loaded. If a policy file exists and permits access from the domain of the loading SWF file, then the file is allowed to access theid3property of the Sound object; otherwise it is not.
However, in Adobe AIR, content in the application security sandbox (content
     installed with the AIR application) are not restricted by these security limitations.
For more information related to security, see the Flash Player Developer Center Topic: Security.
Implementation
    public function get id3():ID3InfoRelated API Elements
Example ( How to use this example )
In the constructor, the sound file is loaded but it is not set to play. Here, it is 
 assumed that the file is in the SWF directory. The system must have permission 
 in order to read the ID3 tags of a loaded sound file. If there is ID3 information in 
 the file and the program is permitted to read it, an Event.ID3 event will 
 be fired and the id3 property of the sound file will be populated. 
 The id3 property contains an ID3Info object with all 
 of the ID3 information.
In the id3Handler() method, the file's ID3 tags
 are stored in id3, an ID3Info class object. A text field is 
 instantiated to display the list of the ID3 tags. The for loop iterates 
 through all the ID3 2.0 tags and appends the name and value to the content of 
 the text field. Using ID3 info (ID3Info) properties, the artist, 
 song name, and album are also appended. ActionScript 3.0 
 and Flash Player 9 and later support ID3 2.0 tags, specifically 2.3 and 2.4.
 If you iterate through properties like in the for loop, only ID3 2.0 tags will appear. 
 However, the data from the earlier versions are also stored in the song's id3 
 property and can be accessed using ID3 info class properties. 
 The tags for the ID3 1.0 are at the end of the file while the ID3 2.0 tags are in 
 the beginning of the file. (Sometimes, the files may have both earlier and later version 
 tags in the same place.) If a file encoded with both version 1.0 and 2.0 tags at the 
 beginning and the end of the file, the method id3Handler() will be invoked twice. 
 It first reads the 2.0 version and then the version 1.0. If only ID3 1.0 tag is available, 
 then the information is accessible via the ID3 info properties, like id3.songname. 
 For ID3 2.0, id3.TITS property will retrieve the song name using the new tag (TITS).
Note that no error handling is written for this example and if the ID3 content is long, the result may go beyond the viewable area.
package {
    import flash.display.Sprite;
    import flash.media.Sound;
    import flash.net.URLRequest;
    import flash.media.ID3Info;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.Event;
    public class Sound_id3Example extends Sprite {
        private var snd:Sound = new Sound();       
        private var myTextField:TextField = new TextField();
        public function Sound_id3Example() {
            snd.addEventListener(Event.ID3, id3Handler);
            snd.load(new URLRequest("mySound.mp3"));
        }
    
        private function id3Handler(event:Event):void {
            var id3:ID3Info = snd.id3;
            myTextField.autoSize = TextFieldAutoSize.LEFT;
            myTextField.border = true;
            myTextField.appendText("Received ID3 Info: \n");
              
            for (var propName:String in id3) {
                myTextField.appendText(propName + " = " + id3[propName] + "\n");
            }
 
            myTextField.appendText("\n" + "Artist: " + id3.artist + "\n");
            myTextField.appendText("Song name: " + id3.songName + "\n");
            myTextField.appendText("Album: " + id3.album + "\n\n"); 
 
            this.addChild(myTextField);
        }
    }
}
| isBuffering | property | 
isBuffering:Boolean  [read-only] | Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
     Returns the buffering state of external MP3 files. If the value is true, 
     any playback is 
     currently suspended while the object waits for more data.
     
     
Implementation
    public function get isBuffering():Boolean| isURLInaccessible | property | 
isURLInaccessible:Boolean  [read-only] | Language Version: | ActionScript 3.0 | 
| Runtime Versions: | Flash Player 10.1, AIR 2 | 
	 Indicates if the Sound.url property has been
	 truncated. When the isURLInaccessible value is true the 
	 Sound.url value is only the domain of the final URL from which the sound loaded.
	 For example, the property is truncated if the sound is loaded from http://www.adobe.com/assets/hello.mp3,
	 and the Sound.url property has the value http://www.adobe.com. 
	 The isURLInaccessible value is true only when all of the following are also true:
	 
	 
- An HTTP redirect occurred while loading the sound file.
- The SWF file calling Sound.load()is from a different domain than the sound file's final URL.
- The SWF file calling Sound.load()does not have permission to access the sound file. Permission is granted to access the sound file the same way permission is granted for theSound.id3property: establish a policy file and use theSoundLoaderContext.checkPolicyFileproperty.
Note: The isURLInaccessible property was added for Flash Player 10.1 and AIR 2.0.
	 However, this property is made available to SWF files of all versions when the
	 Flash runtime supports it. So, using some authoring tools in "strict mode" causes a compilation error. To work around the error
	 use the indirect syntax mySound["isURLInaccessible"], or disable strict mode. If you are using Flash Professional CS5
	 or Flex SDK 4.1, you can use and compile this API for runtimes released before Flash Player 10.1 and AIR 2.
For application content in AIR, the value of this property is always false.
Implementation
    public function get isURLInaccessible():BooleanRelated API Elements
| length | property | 
| url | property | 
url:String  [read-only] | Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
     The URL from which this sound was loaded. This property is applicable only to Sound 
     objects that were loaded using the Sound.load() method. For
     Sound objects that are associated with a sound asset from a SWF file's library, the
     value of the url property is null.
     
     
When you first call Sound.load(), the url property 
     initially has a value of null, because the final URL is not yet known.
     The url property will have a non-null value as soon as an
     open event is dispatched from the Sound object.
The url property contains the final, absolute URL from which a sound was
     loaded. The value of url is usually the same as the value passed to the 
     stream parameter of Sound.load(). 
     However, if you passed a relative URL to Sound.load()
     the value of the url property represents the absolute URL.
     Additionally, if the original URL request is redirected by an HTTP server, the value
     of the url property reflects the final URL from which the sound file was actually
     downloaded.  This reporting of an absolute, final URL is equivalent to the behavior of
     LoaderInfo.url.
In some cases, the value of the url property is truncated; see the 
     isURLInaccessible property for details.
Implementation
    public function get url():StringRelated API Elements
| Sound | () | Constructor | 
public function Sound(stream:URLRequest = null, context:SoundLoaderContext = null)| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
     Creates a new Sound object. If you pass a valid URLRequest object to the 
     Sound constructor, the constructor automatically calls the load() function 
     for the Sound object. 
     If you do not pass a valid URLRequest object to the Sound constructor,
     you must call the load() function for the Sound object yourself, 
     or the stream will not load.
     
     
Once load() is called on a Sound object, you can't later load 
     a different sound file into that Sound object. To load a different sound file,
     create a new Sound object.
load(), 
     you can use the sampleData event handler to load sound dynamically into the Sound object.
     
      Parameters | stream:URLRequest(default =null)—  The URL that points to an external MP3 file. | |
| context:SoundLoaderContext(default =null)—  An optional SoundLoader context object, which can define the buffer time 
     (the minimum number of milliseconds of MP3 data to hold in the Sound object's 
     buffer) and can specify whether the application should check for a cross-domain
     policy file prior to loading the sound. | 
| close | () | method | 
 public function close():void| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
     Closes the stream, causing any download of data to cease.
     No data may be read from the stream after the close()
     method is called.
     
     
Throws
| IOError — The stream could not be closed, or
     the stream was not open. | 
Example ( How to use this example )
Sound.close() method will be called and the sound will stop streaming.
 
 In the constructor, a text field is created for the Start and Stop button. 
 When the user clicks on the text field, the clickHandler() method is invoked.
 It handles the starting and stopping of the sound file. Note that depending on 
 the network connection or when the user clicks the Stop button, much of the file could 
 already have been loaded and it may take a while for the sound file to stop playing. 
 A try...catch block is used to catch any IO error that may occur while 
 closing the stream. For example, if the sound is loaded from a local directory and 
 not streamed, error 2029 is caught, stating, "This URLStream object does not have an open stream."
 
package {
    import flash.display.Sprite;
    import flash.net.URLRequest;
    import flash.media.Sound;    
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.MouseEvent;
    import flash.errors.IOError;
    import flash.events.IOErrorEvent;
    public class Sound_closeExample extends Sprite {
        private var snd:Sound = new Sound();
        private var button:TextField = new TextField();
        private var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
        
        public function Sound_closeExample() {
            button.x = 10;
            button.y = 10;
            button.text = "START";
            button.border = true;
            button.background = true;
            button.selectable = false;
            button.autoSize = TextFieldAutoSize.LEFT;
            button.addEventListener(MouseEvent.CLICK, clickHandler);
            this.addChild(button);
        }
        private function clickHandler(e:MouseEvent):void {
            if(button.text == "START") {
                snd.load(req);
                snd.play();        
                snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
                button.text = "STOP";
            }
            else if(button.text == "STOP") {
                    
                try {
                    snd.close();
                    button.text = "Wait for loaded stream to finish.";
                }
                catch (error:IOError) {
                    button.text = "Couldn't close stream " + error.message;    
                }
            }
        }
        
        private function errorHandler(event:IOErrorEvent):void {
                button.text = "Couldn't load the file " + event.text;
        }
    }
}
| extract | () | method | 
 public function extract(target:ByteArray, length:Number, startPosition:Number = -1):Number| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | Flash Player 10, AIR 1.5 | 
Extracts raw sound data from a Sound object.
This method is designed to be used when you are working 
      with dynamically generated audio, using a function you assign
      to the sampleData event for a different Sound object. 
      That is, you can use this method to extract sound data from a Sound object.
      Then you can write the data to the byte array that another Sound object is using
      to stream dynamic audio.
The audio data is placed in the target byte array starting from the current position of the byte array.
      The audio data is always exposed as 44100 Hz Stereo. The sample type is a 32-bit floating-point value,
      which can be converted to a Number using ByteArray.readFloat(). 
Parameters
| target:ByteArray— A ByteArray object in which the extracted sound samples are placed. | |
| length:Number— The number of sound samples to extract. 
      A sample contains both the left and right channels — that is, two 32-bit floating-point values. | |
| startPosition:Number(default =-1)— The sample at which extraction begins.
          If you don't specify a value, the first call toSound.extract()starts at the beginning
          of the sound; subsequent calls without a value forstartPositionprogress sequentially through the file. | 
| Number— The number of samples written to the ByteArray specified in thetargetparameter. | 
Related API Elements
Example ( How to use this example )
extract() method of the Sound class to access the audio data.
 The mp3 data is loaded into the sourceSnd Sound object. When the
 application loads the mp3 data, it calls the loaded() function
 (the event handler for the complete event of the sourceSnd
 object). A second Sound object, outputSound, is used to play the 
 modified audio. The outputSound object has a sampleData
 event listener; so the object dispatches periodical sampleData events
 once you call the play() method of the object. 
 The upOctave() method returns a byte array of modified audio data
 based on the source audio data. It returns audio that is one octave higher by 
 skipping over every other audio sample in the source data. The event handler for 
 the sampleData event writes the returned byte array to the data 
 property of the outputSound object. The data byte array is 
 appended to the output audio data for the outputSound object.
To test this example, add a test.mp3 file to the same directory as the SWF file.
var sourceSnd:Sound = new Sound();
var outputSnd:Sound = new Sound();
var urlReq:URLRequest = new URLRequest("test.mp3");
sourceSnd.load(urlReq);
sourceSnd.addEventListener(Event.COMPLETE, loaded);
function loaded(event:Event):void
{
    outputSnd.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound);
    outputSnd.play();
}
function processSound(event:SampleDataEvent):void
{
    var bytes:ByteArray = new ByteArray();
    sourceSnd.extract(bytes, 4096);
    event.data.writeBytes(upOctave(bytes));
}
function upOctave(bytes:ByteArray):ByteArray
{
    var returnBytes:ByteArray = new ByteArray();
    bytes.position = 0;
    while(bytes.bytesAvailable > 0)
    {
        returnBytes.writeFloat(bytes.readFloat());
        returnBytes.writeFloat(bytes.readFloat());
        if (bytes.bytesAvailable > 0)
        {
            bytes.position += 8;
        }
    }
    return returnBytes;
}
| load | () | method | 
 public function load(stream:URLRequest, context:SoundLoaderContext = null):void| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
     Initiates loading of an external MP3 file from the specified URL. If you provide
     a valid URLRequest object to the Sound constructor, the constructor calls
     Sound.load() for you. You only need to call Sound.load()
     yourself if you
     don't pass a valid URLRequest object to the Sound constructor or you pass a null
     value.
     
     
Once load() is called on a Sound object, you can't later load 
     a different sound file into that Sound object. To load a different sound file,
     create a new Sound object.
When using this method, consider the following security model:
- Calling Sound.load()is not allowed if the calling file is in the local-with-file-system sandbox and the sound is in a network sandbox.
- Access from the local-trusted or local-with-networking sandbox requires permission from a website through a URL policy file.
- You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.
- You can prevent a SWF file from using this method by setting the 
     allowNetworkingparameter of theobjectandembedtags in the HTML page that contains the SWF content.
In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), the POST operation is subject to the security rules applied to uploads:
- The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
- If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.
Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.
In Adobe AIR, content in the application security sandbox (content
     installed with the AIR application) are not restricted by these security limitations.
For more information related to security, see the Flash Player Developer Center Topic: Security.
Parameters
| stream:URLRequest—  A URL that points to an external MP3 file. | |
| context:SoundLoaderContext(default =null)—  An optional SoundLoader context object, which can define the buffer time 
     (the minimum number of milliseconds of MP3 data to hold in the Sound object's 
     buffer) and can specify whether the application should check for a cross-domain
     policy file prior to loading the sound. | 
Throws
| IOError — A network error caused the load to fail. | |
| SecurityError — Local untrusted files may not communicate with
     the Internet. You can work around this by reclassifying this file
     as local-with-networking or trusted. | |
| SecurityError — You cannot connect to commonly reserved ports. 
     For a complete list of blocked ports, see "Restricting Networking APIs" in the 
     ActionScript 3.0 Developer's Guide. | |
| IOError — Thedigestproperty of thestreamobject is notnull. You should only set thedigestproperty of a URLRequest object
     when calling theURLLoader.load()method when loading a SWZ file (an Adobe 
     platform component). | 
Example ( How to use this example )
In the constructor a URLRequest object is created to identify the location 
 of the sound file, which is a podcast from Adobe. The file is loaded in a try...catch 
 block in order to catch any error that may occur while loading the file. If an IO error 
 occurred, the errorHandler() method also is invoked and the error message 
 is written in the text field intended for the progress report. While a load operation is in 
 progress, a ProgressEvent.PROGRESS event is dispatched and the progressHandler() 
 method is called. Here, ProgressEvent.PROGRESS event is used as a timer for 
 calculating the load progress.
The progressHandler() method divides the bytesLoaded value 
 passed with the ProgressEvent object by the bytesTotal value to 
 arrive at a percentage of the sound data that is being loaded. It then displays these values 
 in the text field. (Note that if the file is small, cached, or the file is in the local directory, 
 the progress may not be noticeable.)
package {
    import flash.display.Sprite;
    import flash.net.URLRequest;
    import flash.media.Sound;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.ProgressEvent;
    import flash.events.IOErrorEvent;
    
    public class Sound_loadExample extends Sprite {
        private var snd:Sound = new Sound();
        private var statusTextField:TextField  = new TextField();
        public function Sound_loadExample(){
            statusTextField.autoSize = TextFieldAutoSize.LEFT;
            var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
            
            try {
            snd.load(req);
            
            snd.play();
            }
            catch (err:Error) {
                trace(err.message);
            }
 
            snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            snd.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                     
            this.addChild(statusTextField);
        }
    
        private function progressHandler(event:ProgressEvent):void {
            var loadTime:Number = event.bytesLoaded / event.bytesTotal;
            var LoadPercent:uint = Math.round(100 * loadTime);
              
            statusTextField.text = "Sound file's size in bytes: " + event.bytesTotal + "\n" 
                                 + "Bytes being loaded: " + event.bytesLoaded + "\n" 
                                 + "Percentage of sound file that is loaded " + LoadPercent + "%.\n";
        }
 
        private function errorHandler(errorEvent:IOErrorEvent):void {
            statusTextField.text = "The sound could not be loaded: " + errorEvent.text;
        }
    }
}
| loadCompressedDataFromByteArray | () | method | 
 public function loadCompressedDataFromByteArray(bytes:ByteArray, bytesLength:uint):void| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 3, Flash Player 11 | 
load MP3 sound data from a ByteArray object into a Sound object. The data will be read from the current ByteArray position and will leave the ByteArray position at the end of the specified bytes length once finished. If the MP3 sound data contains ID3 data ID3 events will be dispatched during this function call. This function will throw an exception if the ByteArray object does not contain enough data.
Parameters
| bytes:ByteArray | |
| bytesLength:uint | 
| loadPCMFromByteArray | () | method | 
 public function loadPCMFromByteArray(bytes:ByteArray, samples:uint, format:String = "float", stereo:Boolean = true, sampleRate:Number = 44100.0):void| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 3, Flash Player 11 | 
Load PCM 32-bit floating point sound data from a ByteArray object into a Sound object. The data will be read from the current ByteArray position and will leave the ByteArray position at the end of the specified sample length multiplied by either 1 channel or 2 channels if the stereo flag is set once finished.
Starting with Flash Player 11.8, the amount of audio data that can be passed to this function is limited. For SWF versions >= 21, this function throws an exception if the amount of audio data passed into this function is more than 1800 seconds. That is, samples / sampleRate should be less than or equal to 1800. For swf versions < 21, the runtime fails silently if the amount of audio data passed in is more than 12000 seconds. This is provided only for backward compatibility.
This function throws an exception if the ByteArray object does not contain enough data.
Parameters
| bytes:ByteArray | |
| samples:uint | |
| format:String(default = "float") | |
| stereo:Boolean(default =true) | |
| sampleRate:Number(default =44100.0) | 
| play | () | method | 
 public function play(startTime:Number = 0, loops:int = 0, sndTransform:flash.media:SoundTransform = null):SoundChannel| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Generates a new SoundChannel object to play back the sound. This method returns a SoundChannel object, which you access to stop the sound and to monitor volume. (To control the volume, panning, and balance, access the SoundTransform object assigned to the sound channel.)
Parameters
| startTime:Number(default =0)— The initial position in milliseconds at which playback should 
     start. | |
| loops:int(default =0)— Defines the number of times a sound loops back to thestartTimevalue
     before the sound channel stops playback. | |
| sndTransform:flash.media:SoundTransform(default =null)— The initial SoundTransform object assigned to the sound channel. | 
| SoundChannel— A SoundChannel object, which you use to control the sound. 
     This method returnsnullif you have no sound card 
     or if you run out of available sound channels. The maximum number of 
     sound channels available at once is 32. | 
Related API Elements
Example ( How to use this example )
The constructor calls the Sound.load() method to start loading the sound data. 
 Next it calls the Sound.play() method which will start playing the sound as soon 
 as enough data has loaded. The Sound.play() method returns a SoundChannel object 
 that can be used to control the playback of the sound. The text field displays the instructions. 
 To make sure the content of where the user wants the sound to start, has already been loaded, 
 the bar Sprite object is created and displayed after the file has finished loading. 
 An Event.COMPLETE event is dispatched when the file is successfully loaded, which 
 triggers the completeHandler() method. The completeHandler() method 
 then creates the bar and adds it to the display list. (A sprite object is used instead of a shape 
 object to support interactivity.) When the user clicks on the bar, the clickHandler() 
 method is triggered.
In the clickHandler() method, the position of x coordinate of the user's click, 
 event.localX, is used to determine where the user wants the file to start. 
 Since the bar is 100 pixels and it starts at x coordinate 100 pixels, it is easy to determine 
 the percentage of the position. Also, since the file is loaded, the length 
 property of the sound file will have the length of the complete file in milliseconds. 
 Using the length of the sound file and the position in the line, a starting position 
 for the sound file is determined. After stopping the sound from playing, the sound file 
 restarts at the selected starting position, which is past as the startTime 
 parameter to the play() method.
 
package {
    import flash.display.Sprite;
    import flash.display.Graphics;
    import flash.events.MouseEvent;
    import flash.media.Sound;;
    import flash.net.URLRequest;
    import flash.media.SoundChannel;
    import flash.events.ProgressEvent;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.IOErrorEvent;
    
    public class Sound_playExample1 extends Sprite {
        private var snd:Sound = new Sound();
        private var channel:SoundChannel = new SoundChannel();
        private var infoTextField:TextField = new TextField();
    
        public function Sound_playExample1() {
            var req:URLRequest = new URLRequest("MySound.mp3");
            
            infoTextField.autoSize = TextFieldAutoSize.LEFT;
            infoTextField.text = "Please wait for the file to be loaded.\n" 
                                + "Then select from the bar to decide where the file should start.";
            
            snd.load(req);               
            channel = snd.play();
            snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            snd.addEventListener(Event.COMPLETE, completeHandler);
            this.addChild(infoTextField);
        }
        private function completeHandler(event:Event):void {                
            infoTextField.text = "File is ready.";
            var bar:Sprite = new Sprite();
            bar.graphics.lineStyle(5, 0xFF0000);
            bar.graphics.moveTo(100, 100);
            bar.graphics.lineTo(200, 100);
            bar.addEventListener(MouseEvent.CLICK, clickHandler);
            this.addChild(bar);
        }
    
        private function clickHandler(event:MouseEvent):void {
            
                var position:uint = event.localX;
                var percent:uint = Math.round(position) - 100;   
                var cue:uint = (percent / 100) * snd.length;
                channel.stop();
                channel = snd.play(cue);    
        }
        private function errorHandler(errorEvent:IOErrorEvent):void {
            infoTextField.text = "The sound could not be loaded: " + errorEvent.text;
        }
    }
}
In the constructor, the sound is loaded and a simple rectangle button sprite object 
 is created. (A sprite object is used instead of a shape object to support interactivity.)
 Here, it is assumed that the sound file is in the same directory as the SWF file. (There 
 is no error handling code for this example.)
Two event listeners are set up to respond to single mouse clicks and double clicks.
 If the user clicks once, the clickHandler() method is invoked, which plays the sound. 
 If the user double clicks on the button, the doubleClickHandler() method is invoked, 
 which will play the sound file twice. The second argument of the play() method is set 
 to 1, which means the sound will loop back once to the starting time of the 
 sound and play again. The starting time, first argument, is set to 0, meaning 
 the file will play from the beginning.
package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.media.Sound;
    import flash.net.URLRequest;
    public class Sound_playExample2 extends Sprite {
        private var button:Sprite = new Sprite(); 
        private var snd:Sound = new Sound();
            
        public function Sound_playExample2() {
            var req:URLRequest = new URLRequest("click.mp3");
            snd.load(req);               
     
            button.graphics.beginFill(0x00FF00);
            button.graphics.drawRect(10, 10, 50, 30);
            button.graphics.endFill();
     
            button.addEventListener(MouseEvent.CLICK, clickHandler);
            button.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);
     
            this.addChild(button);
        }
        private function clickHandler(event:MouseEvent):void {
            snd.play();            
        }
        private function doubleClickHandler(event:MouseEvent):void {
            snd.play(0, 2);        
        }
    }
}
In the constructor, the file is loaded in a try...catch block in order to catch 
 any error that may occur while loading the file. A listener is added to the sound object that 
 will respond to an IOErrorEvent event by calling the errorHandler() method. 
 Another listener is added for the main application that will respond to an Event.ENTER_FRAME 
 event, which is used as the timing mechanism for showing playback progress. Finally, a third listener
 is added for the sound channel that will respond to an Event.SOUND_COMPLETE event (when
 the sound has finished playing), by calling the soundCompleteHandler() method.
 The soundCompleteHandler() method also removes the event listener for the 
 Event.ENTER_FRAME event.
The enterFrameHandler() method divides the bytesLoaded value 
 passed with the ProgressEvent object by the bytesTotal value to 
 arrive at a percentage of the sound data that is being loaded. The percentage of sound data that is 
 being played could be determined by dividing the value of sound channel's position property
 by the length of the sound data. However, if the sound data is not fully loaded, the length
 property of the sound object shows only the size of the sound data that is currently loaded.
 An estimate of the eventual size of the full sound file is calculated by dividing the value 
 of the current sound object's length by the value of the bytesLoaded
 property divided by the value of the bytesTotal property.
Note that if the file is small, cached, or the file is in the local directory, the load progress 
 may not be noticeable. Also the lag time between when the sound data starts loading and the loaded 
 data starts playing is determined by the value of the SoundLoaderContext.buffertime 
 property, which is by default 1000 milliseconds and can be reset.
package {
    import flash.display.Sprite;
    import flash.net.URLRequest;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    
    public class Sound_playExample3 extends Sprite {
        private var snd:Sound = new Sound();
        private var channel:SoundChannel;
        private var statusTextField:TextField  = new TextField();
        public function Sound_playExample3(){
            statusTextField.autoSize = TextFieldAutoSize.LEFT;
           var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
            
            try {
                snd.load(req);
            
                channel = snd.play();
            }
            catch (err:Error) {
                trace(err.message);
            }
                    
            snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            addEventListener(Event.ENTER_FRAME, enterFrameHandler);
            channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
                    
            this.addChild(statusTextField);
        }
    
        private function enterFrameHandler(event:Event):void {    
            var loadTime:Number = snd.bytesLoaded / snd.bytesTotal;
            var loadPercent:uint = Math.round(100 * loadTime);
            var estimatedLength:int = Math.ceil(snd.length / (loadTime));
            var playbackPercent:uint = Math.round(100 * (channel.position / estimatedLength));
      
            statusTextField.text = "Sound file's size is " + snd.bytesTotal + " bytes.\n" 
                                   + "Bytes being loaded: " + snd.bytesLoaded + "\n" 
                                   + "Percentage of sound file that is loaded " + loadPercent + "%.\n"
                                   + "Sound playback is " + playbackPercent + "% complete.";     
        }
 
        private function errorHandler(errorEvent:IOErrorEvent):void {
            statusTextField.text = "The sound could not be loaded: " + errorEvent.text;
        }
        private function soundCompleteHandler(event:Event):void {
            statusTextField.text = "The sound has finished playing.";
            removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
        }
    }
}
| complete | Event | 
flash.events.Eventproperty Event.type =
flash.events.Event.COMPLETE| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Dispatched when data has loaded successfully.
TheEvent.COMPLETE constant defines the value of the type property of a complete event object. 
	
	This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| cancelable | false; there is no default behavior to cancel. | 
| currentTarget | The object that is actively processing the Event object with an event listener. | 
| target | The network object that has completed loading. | 
Related API Elements
| id3 | Event | 
flash.events.Eventproperty Event.type =
flash.events.Event.ID3| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Dispatched by a Sound object when ID3 data is available for an MP3 sound.
TheEvent.ID3 constant defines the value of the type property of an id3 event object. 
	This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| cancelable | false; there is no default behavior to cancel. | 
| currentTarget | The object that is actively processing the Event object with an event listener. | 
| target | The Sound object loading the MP3 for which ID3 data is now available. 
	The targetis not always the object in the display list 
	that registered the event listener. Use thecurrentTargetproperty to access the object in the display list that is currently processing the event. | 
Related API Elements
| ioError | Event | 
flash.events.IOErrorEventproperty IOErrorEvent.type =
flash.events.IOErrorEvent.IO_ERROR| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Dispatched when an input/output error occurs that causes a load operation to fail.
Defines the value of thetype property of an ioError event object.
	This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| cancelable | false; there is no default behavior to cancel. | 
| currentTarget | The object that is actively processing the Event object with an event listener. | 
| errorID | A reference number associated with the specific error (AIR only). | 
| target | The network object experiencing the input/output error. | 
| text | Text to be displayed as an error message. | 
Related API Elements
| open | Event | 
flash.events.Eventproperty Event.type =
flash.events.Event.OPEN| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Dispatched when a load operation starts.
TheEvent.OPEN constant defines the value of the type property of an open event object. 
	
	This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| cancelable | false; there is no default behavior to cancel. | 
| currentTarget | The object that is actively processing the Event object with an event listener. | 
| target | The network object that has opened a connection. | 
Related API Elements
| progress | Event | 
flash.events.ProgressEventproperty ProgressEvent.type =
flash.events.ProgressEvent.PROGRESS| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | AIR 1.0, Flash Player 9, Flash Lite 4 | 
Dispatched when data is received as a load operation progresses.
Defines the value of thetype property of a progress event object.
	
	This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| bytesLoaded | The number of items or bytes loaded at the time the listener processes the event. | 
| bytesTotal | The total number of items or bytes that ultimately will be loaded if the loading process succeeds. | 
| cancelable | false; there is no default behavior to cancel. | 
| currentTarget | The object that is actively processing the Event object with an event listener. | 
| target | The object reporting progress. | 
Related API Elements
| sampleData | Event | 
flash.events.SampleDataEventproperty SampleDataEvent.type =
flash.events.SampleDataEvent.SAMPLE_DATA| Language Version: | ActionScript 3.0 | 
| Runtime Versions: | Flash Player 10, AIR 1.5 | 
Dispatched when the runtime requests new audio data.
Defines the value of thetype property of a SampleDataEvent event object. 
		This event has the following properties:
| Property | Value | 
|---|---|
| bubbles | false | 
| cancelable | false; there is no default behavior to cancel. | 
| position | The point from which audio data is provided. | 
Example ( How to use this example )
var mySound:Sound = new Sound();
function sineWaveGenerator(event:SampleDataEvent):void {
    for ( var c:int=0; c<8192; c++ ) {
        event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25);
        event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25);
    }
}
mySound.addEventListener(SampleDataEvent.SAMPLE_DATA,sineWaveGenerator);
mySound.play();
Related API Elements
package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    import flash.net.URLRequest;
    public class SoundExample extends Sprite {
        private var url:String = "MySound.mp3";
        private var song:SoundChannel;
        public function SoundExample() {
            var request:URLRequest = new URLRequest(url);
            var soundFactory:Sound = new Sound();
            soundFactory.addEventListener(Event.COMPLETE, completeHandler);
            soundFactory.addEventListener(Event.ID3, id3Handler);
            soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            soundFactory.load(request);
            song = soundFactory.play();
        }
        private function completeHandler(event:Event):void {
            trace("completeHandler: " + event);
        }
        private function id3Handler(event:Event):void {
            trace("id3Handler: " + event);
        }
        private function ioErrorHandler(event:Event):void {
            trace("ioErrorHandler: " + event);
        }
        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler: " + event);
        }
    }
}
Thu Dec 4 2014, 05:50 PM -08:00