ActionScript 3.0 Language and Components Reference | All Packages | All Classes | Language Elements | Index | Appendixes | Conventions | Frames No Frames |
Sound

Package | flash.media
Class | public class Sound
Inheritance | Sound EventDispatcher Object

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The Sound class lets you work with sound in an application. The Sound class lets you create a new Sound object, load and play an external MP3 file into that object, close the sound stream, and access data about the sound, such as information about the number of bytes in the stream and ID3 metadata. More detailed control of the sound is performed through the sound source — the SoundChannel or Microphone object for the sound — and through the properties in the SoundTransform class that control the output of the sound to the computer's speakers.

To control sounds that are embedded in a SWF file, use the properties in the SoundMixer class.

To manage sound that is generated dynamically, use the Sound.sampleData event.

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 Flash Player security model:

- Loading and playing a sound is not allowed if the calling SWF 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 SWF is local and tries to load and play a remote sound. A user must grant explicit permission to allow this.
- Certain operations dealing with sound are restricted. The data in a loaded sound cannot be accessed by a SWF file in a different domain unless you implement a URL policy file. Sound-related APIs that fall under this restriction are `Sound.id3`, `SoundMixer.computeSpectrum()`, `SoundMixer.bufferTime`, and the `SoundTransform` class.

For more information related to security, see the following:

- The security chapter in the Programming ActionScript 3.0 book and the latest comments on LiveDocs
- The Flash Player Developer Center Topic: Security

View the examples

See also

flash.net.NetStream
Microphone
SoundChannel
SoundMixer
SoundTransform
Basics of working with sound

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| 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
|  | length : Number [read-only] The length of the current sound in milliseconds. | Sound
|  | prototype : Object [static] A reference to the prototype object of a class or function object. | Object
|  | url : String [read-only] The URL from which this sound was loaded. | Sound

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | Sound(stream:URLRequest = null, context:SoundLoaderContext = null) 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
|  | close():void Closes the stream, causing any download of data to cease. | Sound
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | extract(target:ByteArray, length:Number, startPosition:Number = -1):Number Extracts raw sound data from a Sound object. | Sound
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | load(stream:URLRequest, context:SoundLoaderContext = null):void Initiates loading of an external MP3 file from the specified URL. | Sound
|  | play(startTime:Number = 0, loops:int = 0, sndTransform:SoundTransform = null):SoundChannel Generates a new SoundChannel object to play back the sound. | Sound
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher

Events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | Dispatched when Flash Player gains operating system focus and becomes active. | EventDispatcher
|  | complete | Dispatched when data has loaded successfully. | Sound
|  | deactivate | Dispatched when Flash Player loses operating system focus and is becoming inactive. | EventDispatcher
|  | id3 | Dispatched by a Sound object when ID3 data is available for an MP3 sound. | Sound
|  | ioError | Dispatched when an input/output error occurs that causes a load operation to fail. | Sound
|  | open | Dispatched when a load operation starts. | Sound
|  | progress | Dispatched when data is received as a load operation progresses. | Sound
|  | sampleData | Dispatched when the player requests new audio data. | Sound

Property Detail

bytesLoaded | property

`bytesLoaded:uint` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Returns the currently available number of bytes in this sound object. This is usually only useful for externally loaded files.

Implementation
`public function get bytesLoaded():uint`

bytesTotal | property |

`bytesTotal:int` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Returns the total number of bytes in this sound object.

Implementation
`public function get bytesTotal():int`

id3 | property |

`id3:ID3Info` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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 supports 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 ActionScript 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 ActionScript. You access them by calling `mySound.id3.TFLT`, `mySound.id3.TIME`, and so on.

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 `id3` property 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 a `context` parameter, which is a SoundLoaderContext object. If you set the `checkPolicyFile` property of the SoundLoaderContext object to `true`, Flash Player checks for a URL policy file on the server from which the sound is loaded. If there is a policy file, and the file permits the domain of the loading SWF file, then the file is allowed to access the `id3` property of the Sound object; otherwise it is not.

For more information related to security, see the following:

- The security chapter in the Programming ActionScript 3.0 book and the latest comments on LiveDocs
- The Flash Player Developer Center Topic: Security

Implementation
`public function get id3():ID3Info`

See also

SoundLoaderContext.checkPolicyFile
Example
The following example reads the ID3 information from a sound file and displays it in a text field.

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

Player Version : | Flash Player 9

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`

length | property |

`length:Number` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

The length of the current sound in milliseconds.

Implementation
`public function get length():Number`

url | property |

`url:String` [read-only]

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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'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 will represent 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`.

Implementation
`public function get url():String`

See also

load()
flash.display.LoaderInfo.url
Constructor Detail

Sound | () | Constructor

`public function Sound(stream:URLRequest = null, context:SoundLoaderContext = null)`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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.

Parameters

| `stream:URLRequest` (default = `null`)`` — The URL that points to an external MP3 file.
| `context:SoundLoaderContext` (default = `null`)`` — Minimum number of milliseconds of MP3 data to hold in the Sound object's buffer. The Sound object waits until it has at least this much data before beginning playback and before resuming playback after a network stall. The default value is 1000 (one second).

Method Detail

close | () | method

`public function close():void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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
In the following example, when the user clicks on the Stop button, the `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 |

`flash10 function extract(target:ByteArray, length:Number, startPosition:Number = -1):Number`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

Extracts raw sound data from a Sound object.

This method is designed to be used when you are working with dynamically generated audio, using the `Sound.sampleData` event. For example, you can extract sound data from a Sound object, manipulate it, and then write it to the `SampleDataEvent.data` property of the Sound object that is playing dynamic audio. That Sound object will then play the manipulated 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 44100Hz 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 should be 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 should begin. If you don't specify a value, the first call to `Sound.extract()` starts at the beginning of the sound; subsequent calls without a value for `startPosition` progress sequentially through the file.

Returns

| `Number` — The number of samples that are available in the Sound object.

See also

play()
sampleData

load | () | method |

`public function load(stream:URLRequest, context:SoundLoaderContext = null):void`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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 Flash Player security model:

- Calling `Sound.load()` is not allowed if the calling SWF 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 can prevent a SWF file from using this method by setting the `allowNetworking` parameter of the the `object` and `embed` tags in the HTML page that contains the SWF content.

For more security-related information, see the following:

- The security chapter in the Programming ActionScript 3.0 book and the latest comments on LiveDocs
- The Flash Player Developer Center Topic: Security

Parameters

| `stream:URLRequest` — A URL that points to an external MP3 file.
| `context:SoundLoaderContext` (default = `null`)`` — Minimum number of milliseconds of MP3 data to hold in the Sound object's buffer. The Sound object waits until it has at least this much data before beginning playback and before resuming playback after a network stall. The default value is 1000 (one second).

Throws

| `IOError` — A network error caused the load to fail.
| `SecurityError` — Local untrusted SWF files may not communicate with the Internet. You can work around this by reclassifying this SWF file as local-with-networking or trusted.

See also

Flash Player security
Example
The following example displays the loading progress of a sound file.

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;
            }
        }
    }

play | () | method |

`public function play(startTime:Number = 0, loops:int = 0, sndTransform:SoundTransform = null):SoundChannel`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

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 the `startTime` value before the sound channel stops playback.
| `sndTransform:SoundTransform` (default = `null`)`` — The initial SoundTransform object assigned to the sound channel.

Returns

| `SoundChannel` — A SoundChannel object, which you use to control the sound. This method returns `null` if 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.

See also

SoundChannel.stop()
SoundMixer.stopAll()
Example
In the following example, once the file is loaded, the user using a graphic bar can select the starting position (starting time) of the sound file.

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 following example, depending on whether the user single or double clicks on a button the sound will play once or twice.

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);
            }
        }
    }

The following example displays the loading and playing progress of a sound file.

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);
            }
        }
    }

Event Detail

complete | Event

Event Object Type: `flash.events.Event`
Event.type property = `flash.events.Event.COMPLETE`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when data has loaded successfully.

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.

See also

load()

id3 | Event |

Event Object Type: `flash.events.Event`
Event.type property = `flash.events.Event.ID3`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched by a Sound object when ID3 data is available for an MP3 sound.

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 `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event.

See also

Sound.id3

ioError | Event |

Event Object Type: `flash.events.IOErrorEvent`
IOErrorEvent.type property = `flash.events.IOErrorEvent.IO_ERROR`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when an input/output error occurs that causes a load operation to fail.

Defines the value of the `type` 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.
`target` | The network object experiencing the input/output error.
`text` | Text to be displayed as an error message.

See also

load()

open | Event |

Event Object Type: `flash.events.Event`
Event.type property = `flash.events.Event.OPEN`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when a load operation starts.

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.

See also

load()

progress | Event |

Event Object Type: `flash.events.ProgressEvent`
ProgressEvent.type property = `flash.events.ProgressEvent.PROGRESS`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 9

Dispatched when data is received as a load operation progresses.

Defines the value of the `type` 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 network object reporting progress.

See also

load()

sampleData | Event |

Event Object Type: `flash.events.Event`
Event.type property = `flash.events.Event.SAMPLE_DATA`

Language Version : | ActionScript 3.0

Player Version : | Flash Player 10

Dispatched when the player requests new audio data.

Use this event when you want to manage dynamically generated audio. In this environment, the Sound object doesn't actually contain sound data. Instead, it acts as a socket for sound data that is being streamed to it through the use of the function you assign to this event.

In your callback function, you use the `ByteArray.writeFloat()` method to write to a ByteArray object (`SampleDataEvent.data`) that contains the sampled data want to play.

When you call `Sound.play()`, the player starts calling your event handler, asking for chunks of data that contain sound samples. The player continues to send events as the sound plays back until you stop providing data.

You can also use the `Sound.extract()` method to extract data from a Sound object, which you can manipulate as desired and then write to the dynamic stream for playback.

When you use this event on a Sound object, only the following methods are enabled; using any other methods or properties throws an "invalid call" exception:

- `Sound.extract()`
- `Sound.play()`

Defines the value of the `type` property of a `sampleData` event object.
Example
The following example plays a simple sine wave.

    var mySound:Sound = new Sound();
    function sineWaveGenerator(event:SampleDataEvent):void {
        for ( var c:int=0; c<2048; 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("sampleData",sineWaveGenerator);
    mySound.play();

See also

extract()
play()
Examples How to use examples
SoundExample.as
The following example displays information about sound events that take place as an MP3 file is opened and played. To run this example, place a file named MySound.mp3 in the same directory as your SWF file.

    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);
            }
        }
    }

Submit Feedback on LiveDocs
© 2004-2008 Adobe Systems Incorporated. All rights reserved.
Tue May 20 2008, 04:02 AM -07:00