VCB-331 Rich Media 1
External Sound Objects (Flash AS3)
Introduction
In a previous exercise I detailed the basics of using sound objects. In that tutorial we made use of internal (library) sounds; however, it is often advantageous to keep the sounds out of the Flash file altogether. In this short exercise I will show you how to play external sound files using the Loader() and URLRequest() classes.
External sounds
- You'll need a sound of some sort; if you don't have one handy you can download this zipped file . It contains two songs by Kevin MacLeod from his royalty free music Web site. Note that unlike my previous basic sound tutorial when you were able to use WAV and AIFF files, you must use mp3 files when you use Flash to play external sound files.
- Open a new Flash file and save it as mySoundTest2.fla.
- Place the sound file in the same directory (folder) as the Flash file.
- With external files we don't need to set the linkage or create a class, which is nice. Instead we'll use the load() method of the Sound class. Select the first frame in the timeline and open the script window. We'll start by creating an instance of the Sound class and then load the external file:
var myExternalSound:Sound = new Sound(); myExternalSound.load(new URLRequest("TechTalk.mp3")); myExternalSound.play();The first line of code creates an instance of our Sound class that I've named myExternalSound. This is an arbitrary name that I gave it; you could call it whatever you like (as long as you use standard naming conventions and don't use a word/term that's already part of ActionScript). The second line loads the sound using the loader class and URLRequest class. Note that the referenced song here ("TechTalk") is the song I suggested you download; obviously, if you use a different song, you'll have to change the URL accordingly. The third line uses the play() method of the Sound class to get the sound playing, just as before.
- Given that most of the time we use sound we'll want to have stop buttons (not to mention volume controls and other features), it's a good idea to add a soundChannel to our code that we can utilize for those features:
var myExternalSound:Sound = new Sound(); myExternalSound.load(new URLRequest("TechTalk.mp3")); var myChannel:SoundChannel = new SoundChannel(); myChannel=myExternalSound.play();
Beyond the basics
Once the sound has been loaded, you can start it, stop it, control its volume etc., just like an internal sound. For more information, check out my Using Sound Objects exercise. If you want to create a volume slider, you can try my Volume Slider tutorial.