There are many ways
to embed sound assets in a Flex application, including:
-
Using the
[Embed]
metadata tag in a script
-
Using the
@Embed
directive in MXML to assign
an embedded asset as a property of a component like a Button or
a SoundEffect.
-
Using the
@Embed
directive within a CSS
file
This section describes the first option: how to embed sounds
in ActionScript code within a Flex application using the
[Embed]
metadata
tag.
To embed an asset in ActionScript code, use the
[Embed]
metadata
tag.
Place the sound file in the main source folder or another folder
that is in your project’s build path. When the compiler encounters
an Embed metadata tag, it creates the embedded asset class for you.
You can access the class through a variable of data type Class that
you declare immediately after the
[Embed]
metadata
tag.
The following code embeds a sound named smallSound.mp3 and uses
a variable named
soundClass
to store a reference
to the embedded asset class associated with that sound. The code
then creates an instance of the embedded asset class, casts it as
an instance of the Sound class, and calls the
play()
method
on that instance:
package
{
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundChannel;
public class EmbeddedSoundExample extends Sprite
{
[Embed(source="smallSound.mp3")]
public var soundClass:Class;
public function EmbeddedSoundExample()
{
var smallSound:Sound = new soundClass() as Sound;
smallSound.play();
}
}
}
To use the embedded sound to set a property of a Flex component,
it should be cast as an instance of the mx.core.SoundAsset class
instead of as an instance of the Sound class. For a similar example
that uses the SoundAsset class see “Embedded asset classes” in Learning
ActionScript 3.0.