Working with Sounds
Now that your sound files are ready, let’s see how we can use them. All sound-related classes belong to the flash.media package and will be introduced throughout this chapter.
Loading Sounds
The Sound
class gets access to the audio
information to load the sound file. It is a subclass of the EventDispatcher
class.
As discussed before, your sound can be embedded, it can be loaded as an external file from your application assets directory, or it can be downloaded from a remote server. For the latter, advise your audience to use WiFi over 3G for a better experience.
If you try to play a sound that is not loaded, you will get a runtime error. Create a listener to be notified when the loading is complete, and then play your file:
import flash.media.Sound; import flash.net.URLRequest; import flash.events.Event; var sound:Sound = new Sound(); sound.addEventListener(Event.COMPLETE, onLoaded); var request:URLRequest = new URLRequest("mySound.mp3"); sound.load(request); // sound fully loaded function onLoaded(event:Event):void { sound.removeEventListener(Event.COMPLETE, onLoaded); sound.play(); }
You can inform the user that the file has started to load:
sound.addEventListener(Event.OPEN, onOpen); function onOpen(event:Event):void { trace("sound loading"); }
If it is a large file, create a listener to display the progress:
import flash.events.ProgressEvent; sound.addEventListener(ProgressEvent.PROGRESS, onLoading); function onLoading(event:ProgressEvent):void { // display the percentage ...
Get Developing Android Applications with Adobe AIR now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.