Using Sounds Embedded in the Library and Other Tricks

So, in ActionScript 2.0, there existed such a thing as *attachSound* which would allow you to call on sounds in your library and iterate them in code much like you would call on movieclips in the library.

With ActionScript 3.0, there is no attachSound, so you need to do a little workaround. It took me a while to find this, but here you go:

import flash.utils.getDefinitionByName;
import flash.media.Sound;


var mySound:Sound;

var librarySound:Class = getDefinitionByName ( "nameOfYourSoundasLinkedFromTheLibrary" ) as Class;

mySound = new librarySound();

Basically, anything that you’re referring to as an Object in ActionScript 3.0 seems to require having a class file. So when you go to your library and export your sound objects for ActionScript, a class file is published for each one, and you need to call on these as a class in your code in order to use them like you would an external .mp3 or other audio file.

Now, for the fun part — remember what a pain in the ass it was to trigger some kind of event when an audio file would stop playing in Flash circa ActionScript 2.0? Throw the following code in to the above:

import flash.media.SoundLoaderContext;
import flash.media.SoundChannel;

var myChannel:SoundChannel;

myChannel = mySound.play();
myChannel.addEventListener( Event.SOUND_COMPLETE, AudioDoneAction );

function AudioDoneAction( event:Event ):void
{
	// Do something when the audio is done
}

So basically, the *Sound* class in ActionScript 3.0 allows you to load sounds and play them, but if you want to manipulate them or use them to evaluate other stuff, you want to include the Sound object as a reference in a *SoundChannel* object.

This seems pretty overcomplicated for my simple example here, but think about it this way. What if you had five different external audio files you wanted to load as a playlist for just one slide in an E-Learning piece, and you wanted to trigger different images and text with each audio file. You can code yourself a playlist and trigger changes upon completion of an audio file — and even track where you are in the playlist so that you could have different actions upon completion of the first and/or the last (or really at any defined place in the order of) audio in the playlist.

I couldn’t figure out the embedded audio as class thing on my own. It took a while of experimenting and searching until I found the solution [here](http://www.flepstudio.org/forum/tutorials/449-library-sounds-flash-cs3.html) and [here](http://www.kirupa.com/forum/archive/index.php/f-141-p-2.html).