PackageTop Level
Classpublic class Sound
InheritanceSound Inheritance Object

Player version: Flash Player 5

The Sound class lets you control sound in a movie. You can add sounds to a movie clip from the library while the movie is playing and control those sounds. If you do not specify a target when you create a new Sound object, you can use the methods to control sound for the whole movie.

You must use the constructor new Sound to create a Sound object before calling the methods of the Sound class.



Public Properties
 Property
  checkPolicyFile : Boolean
Specifies whether Flash Player should attempt to download a policy file from the loaded sound's server before beginning to load the sound itself.
  duration : Number
[read-only]The duration of a sound, in milliseconds.
  id3 : Object
[read-only]Provides access to the metadata that is part of an MP3 file.
  position : Number
[read-only]The number of milliseconds a sound has been playing.
 Properties inherited from class Object
 __proto__, __resolve, constructor, prototype
Public Methods
 Method
  
Sound([target:Object])
Creates a new Sound object for a specified movie clip.
  
Attaches the sound specified in the id parameter to the specified Sound object.
  
Returns the number of bytes loaded (streamed) for the specified Sound object.
  
Returns the size, in bytes, of the specified Sound object.
  
Returns the pan level set in the last setPan() call as an integer from -100 (left) to +100 (right).
  
Returns the sound transform information for the specified Sound object set with the last Sound.setTransform() call.
  
Returns the sound volume level as an integer from 0 to 100, where 0 is off and 100 is full volume.
  
loadSound(url:String, isStreaming:Boolean):Void
Loads an MP3 file into a Sound object.
  
setPan(value:Number):Void
Determines how the sound is played in the left and right channels (speakers).
  
setTransform(transformObject:Object):Void
Sets the sound transform (or balance) information, for a Sound object.
  
setVolume(value:Number):Void
Sets the volume for the Sound object.
  
start([secondOffset:Number], [loops:Number]):Void
Starts playing the last attached sound from the beginning if no parameter is specified, or starting at the point in the sound specified by the secondOffset parameter.
  
stop([linkageID:String]):Void
Stops all sounds currently playing if no parameter is specified, or just the sound specified in the idName parameter.
 Methods inherited from class Object
 addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch
Events
 EventSummaryDefined by
  
onID3 = function() {}
Invoked each time new ID3 data is available for an MP3 file that you load using Sound.attachSound() or Sound.loadSound().Sound
  
onLoad = function(success:Boolean) {}
Invoked automatically when a sound loads.Sound
  
onSoundComplete = function() {}
Invoked automatically when a sound finishes playing.Sound
Property detail
checkPolicyFileproperty
public var checkPolicyFile:Boolean

Language version: ActionScript 2.0
Player version: Flash Player 9

Specifies whether Flash Player should attempt to download a policy file from the loaded sound's server before beginning to load the sound itself. This flag is applicable to Sound.loadSound(), but not to Sound objects on which loadSound has not been called.

Set this flag to true when you are loading a sound from outside the calling SWF file's own domain and you expect to need access to the content of that sound from ActionScript. Examples of accessing sound content include referencing the Sound.id3 property to obtain MP3 metadata. If you attempt one of these operations without having specified checkPolicyFile at loading time, you may encounter a security error because the needed policy file has not been downloaded yet.

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

If you set checkPolicyFile to true, Flash Player waits until policy file completion to begin the main download that you specify in loadSound(). Thus, as long as the policy file that you need exists, then as soon as you have received an onLoad event from your Sound object, the policy file download is complete, and you can safely begin performing operations that require the policy file.

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

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

Be careful with checkPolicyFile if you are downloading a sound from a URL that may use server-side HTTP redirects. Flash Player always attempts to retrieve policy files that correspond to the initial URL that you specify in loadSound(). If the final sound file comes from a different URL because of HTTP redirects, then the initially downloaded policy file(s) might not be applicable to the sound's final URL, which is the URL that matters in security decisions.

durationproperty 
duration:Number  [read-only]

Player version: Flash Player 6

The duration of a sound, in milliseconds.

Implementation
    public function get duration():Number

See also


Example
The following example loads a sound and displays the duration of the sound file in the Output panel. The following example loads a sound and writes the duration of the sound file to the log file. Add the following ActionScript to your FLA or AS file.
var my_sound:Sound = new Sound();
my_sound.onLoad = function(success:Boolean) {
    var totalSeconds:Number = this.duration/1000;
    trace(this.duration+" ms ("+Math.round(totalSeconds)+" seconds)");
    var minutes:Number = Math.floor(totalSeconds/60);
    var seconds = Math.floor(totalSeconds)%60;
    if (seconds<10) {
    seconds = "0"+seconds;
    }
    trace(minutes+":"+seconds);
};
my_sound.loadSound("song1.mp3", true);

The following example loads several songs into a SWF file. A progress bar, created using the Drawing API, displays the loading progress. When the music starts and completes loading, information displays in the Output panel.When the music starts and completes loading, information writes to the log file. Add the following ActionScript to your FLA or AS file.

var pb_height:Number = 10;
var pb_width:Number = 100;
var pb:MovieClip = this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());
pb.createEmptyMovieClip("bar_mc", pb.getNextHighestDepth());
pb.createEmptyMovieClip("vBar_mc", pb.getNextHighestDepth());
pb.createEmptyMovieClip("stroke_mc", pb.getNextHighestDepth());
pb.createTextField("pos_txt", pb.getNextHighestDepth(), 0, pb_height, pb_width, 22);

pb._x = 100;
pb._y = 100;

with (pb.bar_mc) {
    beginFill(0x00FF00);
    moveTo(0, 0);
    lineTo(pb_width, 0);
    lineTo(pb_width, pb_height);
    lineTo(0, pb_height);
    lineTo(0, 0);
    endFill();
    _xscale = 0;
}
with (pb.vBar_mc) {
    lineStyle(1, 0x000000);
    moveTo(0, 0);
    lineTo(0, pb_height);
}
with (pb.stroke_mc) {
    lineStyle(3, 0x000000);
    moveTo(0, 0);
    lineTo(pb_width, 0);
    lineTo(pb_width, pb_height);
    lineTo(0, pb_height);
    lineTo(0, 0);
}

var my_interval:Number;
var my_sound:Sound = new Sound();
my_sound.onLoad = function(success:Boolean) {
    if (success) {
    trace("sound loaded");
    }
};
my_sound.onSoundComplete = function() {
    clearInterval(my_interval);
    trace("Cleared interval");
}
my_sound.loadSound("song3.mp3", true);
my_interval = setInterval(updateProgressBar, 100, my_sound);

function updateProgressBar(the_sound:Sound):Void {
    var pos:Number = Math.round(the_sound.position/the_sound.duration*100);
    pb.bar_mc._xscale = pos;
    pb.vBar_mc._x = pb.bar_mc._width;
    pb.pos_txt.text = pos+"%";
}

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

id3property 
id3:Object  [read-only]

Player version: Flash Player 6 — Behavior updated in Flash Player 7.

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 Sound.attachSound() or Sound.loadSound() contains ID3 tags, you can query these properties. Only ID3 tags that use the UTF-8 character set are supported.

Flash Player 6 (6.0.40.0) and later use the Sound.id3 property to support ID3 1.0 and ID3 1.1 tags. Flash Player 7 adds support for ID3 2.0 tags, specifically 2.3 and 2.4. The following table lists the standard ID3 2.0 tags and the type of content the tags represent; you query them in the format my_sound.id3.COMM, my_sound.id3.TIME, and so on. MP3 files can contain tags other than those in this table; Sound.id3 provides access to those tags as well.

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

Flash Player 6 supported several ID3 1.0 tags. If these tags are in not in the MP3 file, but corresponding ID3 2.0 tags are, the ID3 2.0 tags are copied into the ID3 1.0 properties, as shown in the following table. This process provides backward compatibility with scripts that you may have written already that read ID3 1.0 properties.

ID3 2.0 tag Corresponding ID3 1.0 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
Implementation
    public function get id3():Object

See also


Example
The following example traces the ID3 properties of song.mp3 to the Output panel: The following example writes the results of the trace() method for the ID3 properties of song.mp3 to the log file:
var my_sound:Sound = new Sound();
my_sound.onID3 = function(){
    for( var prop in my_sound.id3 ){
    trace( prop + " : "+ my_sound.id3[prop] );
    }
}
my_sound.loadSound("song.mp3", false);

positionproperty 
position:Number  [read-only]

Player version: Flash Player 6

The number of milliseconds a sound has been playing. If the sound is looped, the position is reset to 0 at the beginning of each loop.

Implementation
    public function get position():Number

See also


Example
See Sound.duration for a sample usage of this property.

Constructor detail
Sound()constructor
public function Sound([target:Object])

Player version: Flash Player 5

Creates a new Sound object for a specified movie clip. If you do not specify a target instance, the Sound object controls all of the sounds in the movie.

Parameters
target:Object [optional] — The MovieClip or Button instance on which the Sound object operates.

Example
The following example creates a new Sound object called global_sound. The second line calls setVolume() and adjusts the volume on all sounds in the movie to 50%.
var global_sound:Sound = new Sound();
global_sound.setVolume(50);

The following example creates a new Sound object, passes it the target movie clip my_mc, and calls the start method, which starts any sound in my_mc.

var movie_sound:Sound = new Sound(my_mc);
movie_sound.start();

Method detail
attachSound()method
public function attachSound(id:String):Void

Player version: Flash Player 5

Attaches the sound specified in the id parameter to the specified Sound object. The sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box. You must call Sound.start() to start playing the sound.

To make sure that the sound can be controlled from any scene in the SWF file, place the sound on the main Timeline of the SWF file.

Parameters
id:String — The identifier of an exported sound in the library. The identifier is located in the Linkage Properties dialog box.

Example
The following example attaches the sound logoff_id to my_sound. A sound in the library has the linkage identifier logoff_id.
var my_sound:Sound = new Sound();
my_sound.attachSound("logoff_id");
my_sound.start();

getBytesLoaded()method 
public function getBytesLoaded():Number

Player version: Flash Player 6

Returns the number of bytes loaded (streamed) for the specified Sound object. You can compare the value of getBytesLoaded() with the value of getBytesTotal() to determine what percentage of a sound has loaded.

Returns
Number — An integer indicating the number of bytes loaded.

See also


Example
The following example dynamically creates two text fields that display the bytes that are loaded and the total number of bytes for a sound file that loads into the SWF file. A text field also displays a message when the file finishes loading. Add the following ActionScript to your FLA or AS file:
this.createTextField("message_txt", this.getNextHighestDepth(), 10,10,300,22)
this.createTextField("status_txt", this.getNextHighestDepth(), 10, 50, 300, 40);
status_txt.autoSize = true;
status_txt.multiline = true;
status_txt.border = false;

var my_sound:Sound = new Sound();
my_sound.onLoad = function(success:Boolean) {
    if (success) {
    this.start();
    message_txt.text = "Finished loading";
    }
};
my_sound.onSoundComplete = function() {
    message_txt.text = "Clearing interval";
    clearInterval(my_interval);
};
my_sound.loadSound("song2.mp3", true);
var my_interval:Number;
my_interval = setInterval(checkProgress, 100, my_sound);
function checkProgress(the_sound:Sound):Void {
    var pct:Number = Math.round(the_sound.getBytesLoaded()/the_sound.getBytesTotal()*100);
    var pos:Number = Math.round(the_sound.position/the_sound.duration*100);
    status_txt.text = the_sound.getBytesLoaded()+" of "+the_sound.getBytesTotal()+" bytes ("+pct+"%)"+newline;
    status_txt.text += the_sound.position+" of "+the_sound.duration+" milliseconds ("+pos+"%)"+newline;
}

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

getBytesTotal()method 
public function getBytesTotal():Number

Player version: Flash Player 6

Returns the size, in bytes, of the specified Sound object.

Returns
Number — An integer indicating the total size, in bytes, of the specified Sound object.

See also


Example
See Sound.getBytesLoaded() for a sample usage of this method.

getPan()method 
public function getPan():Number

Player version: Flash Player 5

Returns the pan level set in the last setPan() call as an integer from -100 (left) to +100 (right). (0 sets the left and right channels equally.) The pan setting controls the left-right balance of the current and future sounds in a SWF file.

This method is cumulative with setVolume() or setTransform().

Returns
Number — An integer.

See also


Example
The following example creates a slider bar using the Drawing API. When the user drags the slider bar, the pan level of the loaded sound changes. The current pan level is displayed in a dynamically created text field. Add the following ActionScript to your FLA or AS file:
var bar_width:Number = 200;
this.createEmptyMovieClip("bar_mc", this.getNextHighestDepth());
with (bar_mc) {
    lineStyle(4, 0x000000);
    moveTo(0, 0);
    lineTo(bar_width+4, 0);
    lineStyle(0, 0x000000);
    moveTo((bar_width/2)+2, -8);
    lineTo((bar_width/2)+2, 8);
}
bar_mc._x = 100;
bar_mc._y = 100;

this.createEmptyMovieClip("knob_mc", this.getNextHighestDepth());
with (knob_mc) {
    lineStyle(0, 0x000000);
    beginFill(0xCCCCCC);
    moveTo(0, 0);
    lineTo(4, 0);
    lineTo(4, 10);
    lineTo(0, 10);
    lineTo(0, 0);
    endFill();
}
knob_mc._x = bar_mc._x+(bar_width/2);
knob_mc._y = bar_mc._y-(knob_mc._height/2);

knob_mc.left = knob_mc._x-(bar_width/2);
knob_mc.right = knob_mc._x+(bar_width/2);
knob_mc.top = knob_mc._y;
knob_mc.bottom = knob_mc._y;

knob_mc.onPress = function() {
    this.startDrag(false, this.left, this.top, this.right, this.bottom);
};
knob_mc.onRelease = panSound;
knob_mc.onReleaseOutside = panSound;

function panSound():Void { {
    this.stopDrag();
    var multiplier:Number = 100/(this.right-this.left)*2;
    var pan:Number = (this._x-this.left-(bar_width/2))*multiplier;
    my_sound.setPan(pan);
    pan_txt.text = my_sound.getPan();
};

var my_sound:Sound = new Sound();
my_sound.loadSound("song2.mp3", true);
this.createTextField("pan_txt", this.getNextHighestDepth(), knob_mc._x, knob_mc._y+knob_mc._height, 20, 22);
pan_txt.selectable = false;
pan_txt.autoSize = "center";
pan_txt.text = my_sound.getPan();

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

getTransform()method 
public function getTransform():Object

Player version: Flash Player 5

Returns the sound transform information for the specified Sound object set with the last Sound.setTransform() call.

Returns
Object — An object with properties that contain the channel percentage values for the specified sound object.

See also


Example
The following example attaches four movie clips from a symbol in the library (linkage identifier: knob_id) that are used as sliders (or knobs) to control the sound file that loads into the SWF file. These sliders control the transform object, or balance, of the sound file. For more information, see the entry for Sound.setTransform(). Add the following ActionScript to your FLA or AS file:
var my_sound:Sound = new Sound();
my_sound.loadSound("song1.mp3", true);
var transform_obj:Object = my_sound.getTransform();

this.createEmptyMovieClip("transform_mc", this.getNextHighestDepth());
transform_mc.createTextField("transform_txt", transform_mc.getNextHighestDepth, 0, 8, 120, 22);
transform_mc.transform_txt.html = true;

var knob_ll:MovieClip = transform_mc.attachMovie("knob_id", "ll_mc", transform_mc.getNextHighestDepth(), {_x:0, _y:30});
var knob_lr:MovieClip = transform_mc.attachMovie("knob_id", "lr_mc", transform_mc.getNextHighestDepth(), {_x:30, _y:30});
var knob_rl:MovieClip = transform_mc.attachMovie("knob_id", "rl_mc", transform_mc.getNextHighestDepth(), {_x:60, _y:30});
var knob_rr:MovieClip = transform_mc.attachMovie("knob_id", "rr_mc", transform_mc.getNextHighestDepth(), {_x:90, _y:30});

knob_ll.top = knob_ll._y;
knob_ll.bottom = knob_ll._y+100;
knob_ll.left = knob_ll._x;
knob_ll.right = knob_ll._x;
knob_ll._y = knob_ll._y+(100-transform_obj['ll']);
knob_ll.onPress = pressKnob;
knob_ll.onRelease = releaseKnob;
knob_ll.onReleaseOutside = releaseKnob;

knob_lr.top = knob_lr._y;
knob_lr.bottom = knob_lr._y+100;
knob_lr.left = knob_lr._x;
knob_lr.right = knob_lr._x;
knob_lr._y = knob_lr._y+(100-transform_obj['lr']);
knob_lr.onPress = pressKnob;
knob_lr.onRelease = releaseKnob;
knob_lr.onReleaseOutside = releaseKnob;

knob_rl.top = knob_rl._y;
knob_rl.bottom = knob_rl._y+100;
knob_rl.left = knob_rl._x;
knob_rl.right = knob_rl._x;
knob_rl._y = knob_rl._y+(100-transform_obj['rl']);
knob_rl.onPress = pressKnob;
knob_rl.onRelease = releaseKnob;
knob_rl.onReleaseOutside = releaseKnob;

knob_rr.top = knob_rr._y;
knob_rr.bottom = knob_rr._y+100;
knob_rr.left = knob_rr._x;
knob_rr.right = knob_rr._x;
knob_rr._y = knob_rr._y+(100-transform_obj['rr']);
knob_rr.onPress = pressKnob;
knob_rr.onRelease = releaseKnob;

knob_rr.onReleaseOutside = releaseKnob;

updateTransformTxt();

function pressKnob() {
    this.startDrag(false, this.left, this.top, this.right, this.bottom);
}
function releaseKnob() {
    this.stopDrag();
    updateTransformTxt();
}
function updateTransformTxt() {
    var ll_num:Number = 30+100-knob_ll._y;
    var lr_num:Number = 30+100-knob_lr._y;
    var rl_num:Number = 30+100-knob_rl._y;
    var rr_num:Number = 30+100-knob_rr._y;
    my_sound.setTransform({ll:ll_num, lr:lr_num, rl:rl_num, rr:rr_num});
    transform_mc.transform_txt.htmlText = "<textformat tabStops='[0,30,60,90]'>";
    transform_mc.transform_txt.htmlText += ll_num+"\t"+lr_num+"\t"+rl_num+"\t"+rr_num;
    transform_mc.transform_txt.htmlText += "</textformat>";
}

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

getVolume()method 
public function getVolume():Number

Player version: Flash Player 5

Returns the sound volume level as an integer from 0 to 100, where 0 is off and 100 is full volume. The default setting is 100.

Returns
Number — An integer.

See also


Example
The following example creates a slider using the Drawing API and a movie clip that is created at runtime. A dynamically created text field displays the current volume level of the sound playing in the SWF file. Add the following ActionScript to your AS or FLA file:
var my_sound:Sound = new Sound();
my_sound.loadSound("song3.mp3", true);

this.createEmptyMovieClip("knob_mc", this.getNextHighestDepth());

knob_mc.left = knob_mc._x;
knob_mc.right = knob_mc.left+100;
knob_mc.top = knob_mc._y;
knob_mc.bottom = knob_mc._y;

knob_mc._x = my_sound.getVolume();

with (knob_mc) {
    lineStyle(0, 0x000000);
    beginFill(0xCCCCCC);
    moveTo(0, 0);
    lineTo(4, 0);
    lineTo(4, 18);
    lineTo(0, 18);
    lineTo(0, 0);
    endFill();
}

knob_mc.createTextField("volume_txt", knob_mc.getNextHighestDepth(), knob_mc._width+4, 0, 30, 22);
knob_mc.volume_txt.text = my_sound.getVolume();

knob_mc.onPress = function() {
    this.startDrag(false, this.left, this.top, this.right, this.bottom);
    this.isDragging = true;
};
knob_mc.onMouseMove = function() {
    if (this.isDragging) {
    this.volume_txt.text = this._x;
    }
}
knob_mc.onRelease = function() {
    this.stopDrag();
    this.isDragging = false;
    my_sound.setVolume(this._x);
    
};

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

loadSound()method 
public function loadSound(url:String, isStreaming:Boolean):Void

Player version: Flash Player 6

Loads an MP3 file into a Sound object. You can use the isStreaming parameter to indicate whether the sound is an event or a streaming sound.

Event sounds are completely loaded before they play. They are managed by the ActionScript Sound class and respond to all methods and properties of this class.

Streaming sounds play while they are downloading. Playback begins when sufficient data has been received to start the decompressor.

All MP3s (event or streaming) loaded with this method are saved in the browser's file cache on the user's system.

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

For more information related to security, see the following:

Note: IPv6 (Internet Protocol version 6) is supported in Flash Player 9.0.115.0 and later. IPv6 is a version of Internet Protocol that supports 128-bit addresses (an improvement on the earlier IPv4 protocol that supports 32-bit addresses). You might need to activate IPv6 on your networking interfaces. For more information, see the Help for the operating system hosting the data. If IPv6 is supported on the hosting system, you can specify numeric IPv6 literal addresses in URLs enclosed in brackets ([]), as in the following.

      rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]:1935/test
      

Parameters
url:String — The location on a server of an MP3 sound file.
 
isStreaming:Boolean — A Boolean value that indicates whether the sound is a streaming sound (true) or an event sound (false).

See also


Example
The following example loads an event sound, which cannot play until it is fully loaded:
var my_sound:Sound = new Sound();
my_sound.loadSound("song1.mp3", false);

The following example loads a streaming sound:

var my_sound:Sound = new Sound();
my_sound.loadSound("song1.mp3", true);

setPan()method 
public function setPan(value:Number):Void

Player version: Flash Player 5

Determines how the sound is played in the left and right channels (speakers). For mono sounds, pan determines which speaker (left or right) the sound plays through.

Parameters
value:Number — An integer specifying the left-right balance for a sound. The range of valid values is -100 to 100, where -100 uses only the left channel, 100 uses only the right channel, and 0 balances the sound evenly between the two channels.

See also


Example
See Sound.getPan() for a sample usage of this method.

setTransform()method 
public function setTransform(transformObject:Object):Void

Player version: Flash Player 5

Sets the sound transform (or balance) information, for a Sound object.

The soundTransformObject parameter is an object that you create using the constructor method of the generic Object class with parameters specifying how the sound is distributed to the left and right channels (speakers).

Sounds use a considerable amount of disk space and memory. Because stereo sounds use twice as much data as mono sounds, it is generally best to use 22-KHz 6-bit mono sounds. You can use setTransform() to play mono sounds as stereo, play stereo sounds as mono, and to add interesting effects to sounds.

The properties for the soundTransformObject are as follows:

ll - A percentage value specifying how much of the left input to play in the left speaker (0-100).

lr - A percentage value specifying how much of the right input to play in the left speaker (0-100).

rr - A percentage value specifying how much of the right input to play in the right speaker (0-100).

rl - A percentage value specifying how much of the left input to play in the right speaker (0-100).

The net result of the parameters is represented by the following formula:

leftOutput = left_input * ll + right_input * lr
rightOutput = right_input * rr + left_input * rl

The values for left_input or right_input are determined by the type (stereo or mono) of sound in your SWF file.

Stereo sounds divide the sound input evenly between the left and right speakers and have the following transform settings by default:

ll = 100
lr = 0
rr = 100
rl = 0

Mono sounds play all sound input in the left speaker and have the following transform settings by default:

ll = 100
lr = 100
rr = 0
rl = 0
Parameters
transformObject:Object — An object created with the constructor for the generic Object class.

See also


Example
The following example illustrates a setting that can be achieved by using setTransform(), but cannot be achieved by using setVolume() or setPan(), even if they are combined.

The following code creates a new soundTransformObject object and sets its properties so that sound from both channels will play only in the left channel.

var mySoundTransformObject:Object = new Object();
mySoundTransformObject.ll = 100;
mySoundTransformObject.lr = 100;
mySoundTransformObject.rr = 0;
mySoundTransformObject.rl = 0;

To apply the soundTransformObject object to a Sound object, you then need to pass the object to the Sound object using setTransform() as follows:

my_sound.setTransform(mySoundTransformObject);

The following example plays a stereo sound as mono; the soundTransformObjectMono object has the following parameters:

var mySoundTransformObjectMono:Object = new Object();
mySoundTransformObjectMono.ll = 50;
mySoundTransformObjectMono.lr = 50;
mySoundTransformObjectMono.rr = 50;
mySoundTransformObjectMono.rl = 50;
my_sound.setTransform(mySoundTransformObjectMono);

This example plays the left channel at half capacity and adds the rest of the left channel to the right channel; the soundTransformObjectHalf object has the following parameters:

var mySoundTransformObjectHalf:Object = new Object();
mySoundTransformObjectHalf.ll = 50;
mySoundTransformObjectHalf.lr = 0;
mySoundTransformObjectHalf.rr = 100;
mySoundTransformObjectHalf.rl = 50;
my_sound.setTransform(mySoundTransformObjectHalf);

var mySoundTransformObjectHalf:Object = {ll:50, lr:0, rr:100, rl:50};

Also see the example for Sound.getTransform().

setVolume()method 
public function setVolume(value:Number):Void

Player version: Flash Player 5

Sets the volume for the Sound object.

Parameters
value:Number — A number from 0 to 100 representing a volume level. 100 is full volume and 0 is no volume. The default setting is 100.

See also


Example
See Sound.getVolume() for a sample usage of this method.

start()method 
public function start([secondOffset:Number], [loops:Number]):Void

Player version: Flash Player 5

Starts playing the last attached sound from the beginning if no parameter is specified, or starting at the point in the sound specified by the secondOffset parameter.

Parameters
secondOffset:Number [optional] — A parameter that lets you start playing the sound at a specific point. For example, if you have a 30-second sound and want the sound to start playing in the middle, specify 15 for the secondOffset parameter. The sound is not delayed 15 seconds, but rather starts playing at the 15-second mark.
 
loops:Number [optional] — A parameter that lets you specify the number of times the sound should play consecutively. This parameter is not available if the sound is a streaming sound.

See also


Example
The following example creates a new Sound object, and loads a sound. Loading the sound is handled by the onLoad handler, which allows you to start the song after it is successfully loaded. Then the sound starts playing using the start() method. Create a new FLA file, and add the following ActionScript to your FLA or AS file. For this example to work, you must have an MP3 called song1.mp3 in the same directory as your FLA or AS file.
this.createTextField("status_txt", this.getNextHighestDepth(), 0,0,100,22);

// create a new Sound object
var my_sound:Sound = new Sound();
// if the sound loads, play it; if not, trace failure loading
my_sound.onLoad = function(success:Boolean) {
    if (success) {
    my_sound.start();
    status_txt.text = "Sound loaded";
    } else {
    status_txt.text = "Sound failed";
    }
};
// load the sound
my_sound.loadSound("song1.mp3", true);

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

stop()method 
public function stop([linkageID:String]):Void

Player version: Flash Player 5

Stops all sounds currently playing if no parameter is specified, or just the sound specified in the idName parameter.

Parameters
linkageID:String [optional] — A parameter specifying a specific sound to stop playing. The idName parameter must be enclosed in quotation marks (" ").

See also


Example
The following example uses two buttons, stop_btn and play_btn, to control the playback of a sound that loads into a SWF file. Add two buttons to your document and add the following ActionScript to your FLA or AS file:
var my_sound:Sound = new Sound();
my_sound.loadSound("song1.mp3", true);

stop_btn.onRelease = function() {
    trace("sound stopped");
    my_sound.stop();
};
play_btn.onRelease = function() {
    trace("sound started");
    my_sound.start();
};

Event detail
onID3event handler

public onID3 = function() {}

Player version: Flash Player 7

Invoked each time new ID3 data is available for an MP3 file that you load using Sound.attachSound() or Sound.loadSound(). This handler provides access to ID3 data without polling. If both ID3 1.0 and ID3 2.0 tags are present in a file, this handler is called twice.


Example
The following example outputs the ID3 properties of the song1.mp3 file (which is in the same directory as the SWF file):
var my_sound:Sound = new Sound();

my_sound.onID3 = function() {
    for (var prop in this.id3) {
        trace(prop + ": " + this.id3[prop])
    }
};
    
my_sound.loadSound("song1.mp3", true);

See also

onLoadevent handler 

public onLoad = function(success:Boolean) {}

Player version: Flash Player 6

Invoked automatically when a sound loads. You must create a function that executes when the this handler is invoked. You can use either an anonymous function or a named function (for an example of each, see Sound.onSoundComplete). You should define this handler before you call mySound.loadSound().

Parameters
success:Boolean — A Boolean value of true if my_sound has been loaded successfully, false otherwise.

Example
The following example creates a new Sound object, and loads a sound. Loading the sound is handled by the onLoad handler, which allows you to start the song after it is successfully loaded. Create a new FLA file, and add the following ActionScript to your FLA or AS file. For this example to work, you must have an MP3 called song1.mp3 in the same directory as your FLA or AS file.
this.createTextField("status_txt", this.getNextHighestDepth(), 0,0,100,22);

// create a new Sound object
var my_sound:Sound = new Sound();
// if the sound loads, play it; if not, trace failure loading
my_sound.onLoad = function(success:Boolean) {
if (success) {
my_sound.start();
status_txt.text = "Sound loaded";
} else {
status_txt.text = "Sound failed";
}
};
// load the sound
my_sound.loadSound("song1.mp3", true);

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components' DepthManager class instead of the MovieClip.getNextHighestDepth() method.

See also

onSoundCompleteevent handler 

public onSoundComplete = function() {}

Player version: Flash Player 6

Invoked automatically when a sound finishes playing. You can use this handler to trigger events in a SWF file when a sound finishes playing.

You must create a function that executes when this handler is invoked. You can use either an anonymous function or a named function.


Example
Usage 1: The following example uses an anonymous function:
var my_sound:Sound = new Sound();
my_sound.attachSound("mySoundID");
my_sound.onSoundComplete = function() {
trace("mySoundID completed");
};
my_sound.start();
Usage 2: The following example uses a named function:
function callback1() {
trace("mySoundID completed");
}
var my_sound:Sound = new Sound();
my_sound.attachSound("mySoundID");
my_sound.onSoundComplete = callback1;
my_sound.start();

See also