Game Development Reference
In-Depth Information
Listing 9-1. Creating a Sound Instance Using createInstance
var mySound = createjs.Sound.createInstance("myID");
mySound.setVolume(.5);
mySound.addEventListener("fileload", handleComplete);
function handleComplete(e){
mySound.play();
}
In Listing 9-1, methods were assigned directly to the sound instance, as opposed to passing them into the constructor.
Registering Sounds
Before playing sounds, you must register them. This was covered in Chapter 1 when introducing SoundJS. As a recap,
the following is an example of how a sound is registered:
createjs.Sound.registerSound("path/sound.mp3", "soundId", 4);
The first parameter is the path to the sound file, and the second is the id, which will be used when accessing
it later for playback. The third parameter is one that was not previously covered, and it dictates the number of
concurrent sounds that should be allowed to play.
It's unlikely that you will only play one sound in your game, so registering multiple files is a must. You can handle
this by building a manifest, similar to when using PreloadJS. Listing 9-2 shows a series of sounds being registered.
Listing 9-2. Registering Multiple Sound Files
var manifest = [
{src:"boom.mp3", id:"boom"},
{src:"snap.mp3 ", id:"snap", data:6},
{src:"crack.mp3 ", id:"crack"}
];
createjs.Sound.alternateExtensions = ["ogg"];
createjs.Sound.registerManifest(manifest, "sounds/");
If you want to load in multiple file types for each sound, you'll need to set the alternateExtensions property on
Sound . In this example, an ogg file will load, if needed, for each sound object in the manifest. You want to include at
least these two file types, mp3 and ogg , so you can be assured your sound will play across all browsers and devices.
The second object in the previous manifest example includes a third property, data . This value is used to set the
number of allowed concurrent sounds to play, similar to the third parameter that is used in the registerSound method.
createjs.Sound.registerSound("boom.mp3", "snap", 6 );
Preloading Sounds with PreloadJS
Because you will be preloading several assets, along with registering multiple sounds, it would be convenient to
handle the entire process with one manifest using PreloadJS. Luckily, this can be achieved by tacking on the sound
assets to the load queue's manifest. PreloadJS will handle and register the sound files appropriately as the files are
loaded into your application by installing the plug-in createjs.Sound . Listing 9-3 shows how you can mix file types,
including sounds, into one manifest for preloading.
 
Search WWH ::




Custom Search