ActionScript 3.0 Design Patterns

(Chris Devlin) #1
When to Use the Singleton Pattern | 117

let it happen to your applications either. Here’s another situation where a Singleton


can come in handy.


To get started, we need to take a look at how we can play an MP3 file in Flash CS3.


We won’t even consider the idea of importing an MP3 file into the main Timeline


and bloating our SWF file. Rather, we need to take a quick look at how ActionScript


3.0 deals with sound and externally accessed MP3 files.


The classes relating to sound can be found in theflash.mediapackage. Of the five


sound-related classes, we’ll need only theSoundandSoundChannelclasses. We’re


going to access an external file (the MP3 file), so we’ll need theflash.net.URLRequest


class as well. The necessary minimum sequence can be seen in the following


pseudocode:


var mySound:Sound = new Sound( );
var myChannel:SoundChannel = new SoundChannel;
var myTune:URLRequest= new URLRequest(string);
mySound.load(myTune);
myChannel=mySound.play( );

Using the following script, we can create the actual method:


public function playMe(song:String):void
{
_tuneUp=new Sound( );
_tuneIn=new URLRequest(song);
_tuneUp.load(_tuneIn);
_goChannel=_tuneUp.play( );
}

The function has a single parameter, which is a string variable that will be the name


of the song (MP3 file). You might want to think of the song parameter as a URL,


because that’s actually what it is. However, it makes perfect sense to reference it as a


song because the individual MP3 files are individual tunes. Given the way the func-


tion’s designed, there’s a place for only a single sound. Because the method resides in


a Singleton class, there’s also going to be only a single instance, guaranteeing that


only one tune at a time will be played.


However, before we go further, we need to consider how theSoundChannelclass


works. As soon as theSound.play( )method is assigned to theSoundChannelinstance,


the song starts playing. If, using the same instance of theSoundandSoundChannel


classes, you load and play another MP3 file, it’s going to start playing as well. As far


as the instances are concerned, there’s no contraction because they’ve done their job


and set the first MP3 file merrily on its way. So they’re finished. Using exactly the


same instance, they’re willing to do it again with another MP3 file even if the first


one’s still playing. The two will overlap, and because that’s one of the things we


want to prevent, the code will have to find whether there’s aSoundChannelinstance


with an assigned value around. This is done by testing theSoundChannelinstance for


anullvalue. If anullvalue is found, the script just goes ahead and activates the code

Free download pdf