SoundWrapper class for SoundJS

CreateJS libraries are very helpful in creating stunning html5 games and apps. This library has a SoundJS library which can be used to play sounds. It can decide which one to load according to the device capability. However, while coding games, we may need to play musics, play sound effects, stop, fade, crossfade etc. For this, we have to manually call some methods. For fading sounds we have to create a loop and reduce the volume of a sound.

What if we could create a static class which helps on doing these. Let’s take a look at the SoundManager class.
var SM = (function(){
    var musics = {};
    /**
     * CreateJS Sound Manager
     * @returns {null}
     */
    function SM(){
        throw new Error("This class can't be instantiated");
        return null;
    }
    
    /**
     * Play music. This is only for playing musics. Use SM.playSound to play sound effects
     * @static
     * @param {String} id
     * @param {Number} repeat Number of times to repeat,0-once,-1-loop @default 0
     * @param {Number} fadeIn Number of milliseconds to fade in
     * @returns {void}
     */
    SM.playMusic = function(id,repeat,fadeIn){
        if(musics[id] && musics[id].playing){
            return;
        }
        repeat = repeat||0;
        fadeIn = (!fadeIn)?0:fadeIn;
        var instance = createjs.Sound.play(id);
        instance.volume = (fadeIn!==0)?0:1;
        var o = {
            instance    : instance,
            playing     : true,
            repeat      : (repeat>=0)?repeat:0,
            loop        : (repeat===-1)?true:false,
            fadeStep    : 1000/(60*fadeIn),
            fadeType    : "FADE_IN"
        };
        musics[id] = o;
        instance.addEventListener("complete",function(){
            SM.musicComplete(o);
        });
    };
    SM.update = function(){
        for(var id in musics){
            var o = musics[id];
            if(o.playing){
                if(o.fadeType === "FADE_IN"){
                    o.instance.volume += o.fadeStep;
                    if(o.instance.volume >= 1){
                        o.instance.volume = 1;
                    }
                }else{
                    o.instance.volume -= o.fadeStep;
                    if(o.instance.volume <= 0){
                        o.instance.volume = 0;
                        SM.stopMusic(id);
                    }
                }
            }
        }
    };
   SM.musicComplete = function(o){
        o.playing = false;
        o.repeat -= 1;
        if(o.loop===true){
            o.instance.play();
            o.playing = true;
        }else if(o.repeat>0){
            o.instance.play();
            o.playing = true;
        }
    };
    /**
     * Stop a playing music
     * @static
     * @param {String} id
     * @param {Number}  fadeOut Number of milliseconds to fadeOut
     * @returns {void}
     */
    SM.stopMusic = function(id,fadeOut){
        var o = musics[id];
        fadeOut = (!fadeOut)?0:fadeOut;
        if(o && o.playing){
            o.fadeType = "FADE_OUT";
            o.fadeStep = (o.instance.volume*1000)/(60*fadeOut);
        }
    };
    /**
     * Play a sound. Use this only to play a sound effect. If it is music, use CSM.playMusic instead
     * @param {String} id
     * @returns {void}
     */
    SM.playSound = function(id){
        createjs.Sound.play(id);
    };
    /**
     * Stop a sound
     * @param {String} id
     * @returns {void}
     */
    SM.stopSound = function(id){
        createjs.Sound.stop(id);
    };
 /**
     * Stop playing all sounds
     * @param {type} fadeOut
     * @returns {void}
     */
    SM.stopAllMusics = function(fadeOut){
        for(var id in musics){
            SM.stopMusic(id,fadeOut);
        }
    };

    return SM;
})();

The above class is set to be a static class so that it can be accessed from anywhere.
playMusic(id,repeat,fadeIn)
id – id of the music that used to load the music
repeat – How many times to repeat the music, -1 to loop indefinitely
fadeIn – Fade in time in milliseconds
stopMusic(id, fadeOut)
id – id of the music
fadeOut – Fade out time in milliseconds

playSound(id)
stopSound(id)

These are used to play and stop sound effects.

Also Read:   Creating a PHP website using MVC – 3 Creating a Database Wrapper

update()

This update to be called on every frame per second. You can see the number 60 on two places in the above class. It is the default fps value which can be changed manually if needed.

To crossfade two musics(game music to menu music), call the SoundManager like this.

SM.stopMusic(“game”,2000);
SM.playMusic(“menu”,2000);

Never miss any content from Codetuto!

Subscribe to Codetuto Newsletter and be the first to recieve our latest posts and tutorials

Subscribe Now For Free

[Total: 0    Average: 0/5]
  • Thanks for this class.
    Just a mistake for me :
    I replace line 54 by SM.stopSound(id); if not i have a javascript error causing by an NaN fadeStep

  • Yes, Thanks for your comment.
    Updated the code.

  • SM.stopMusic(“game”,-1,2000); error, -1 not needed, it do fadeStep negative and sound never stop