Using SoundJS for games

So I was building a new game and wanted to include some sounds and an ambient sound as background music. So I bought a sound from Envato Audio Jungle, and also I asked my cousin to make me an ambient/sci-fi/space sound… He came up with a rather nice composition for a space game.
So I wanted to incorporate all these into my game, so I used one of the best libraries for javascript sound out there, SoundJS

What I did however is to create a custom javascript function/class to handle all of the game sounds and have them ready for playback when I need to fire a bullet or stop the background-sound.

EXAMPLE Here

This is how I did it:

Check for support

First we create the main function.


function sounds(){
    
    var $this = this;
    
    ///////////////////
    
    this.config = new Array();
    this.registeredSounds = new Array();
    var onLoad;
    checkSupport();
    
    function checkSupport(){
        if (!createjs.Sound.initializeDefaultPlugins()) { return false; }
    }

return this;
};

This code here creates a sounds() function and checks for some sound plugins that are needed for SoundJS to work

And we instantiate it:


var _sound = new sounds();


Load the sounds

We check if all the plugins are supported and we load-up the sound files.


if(_sound !== false){
        console.log(_sound);
        _sound.preloadSound("assets/sounds/","metalShot.mp3","metalShot.ogg","T0Shot");
        _sound.preloadSound("assets/sounds/","bg.mp3","bg.ogg","bg",true);
        $(document).on("soundReady", function(){
            // largest sound file finished loading, we can continue execution //
        });
    }

For this to work we need to create the appropriate functions inside our function sounds()


this.preloadSound = function(path, track,track2, identifier,onLoad){
        
        console.log(path+track+"|"+path+track2);
        var id = ("track_"+identifier);
        var manifest = [
        {
            id:id,
            src:path+track+"|"+path+track2
        }
        ];
        
        createjs.Sound.registerSound({id:id, src:path+track});
        createjs.Sound.registerSound({id:id, src:path+track2});
        
        onLoad = id;
        this.registeredSounds["track_"+identifier] = manifest[0].id;
        if(identifier === "bg"){
            createjs.Sound.addEventListener("fileload", onloadSound);
        }
      
        return manifest[0].id;
    }
    
    function onloadSound(e){
        console.log(e);
        var trackID = e.currentTarget.id;
        createjs.Sound.removeAllEventListeners();
        
        var id = $this.registeredSounds[trackID];
        
        $.event.trigger({
            type: "soundReady",
            message: "bg sound is ready",
            time: new Date()
        });
        
    }

Here we declare the id of the item that will be loaded and stored inside SoundJS core for future use, and by that ID we can call it and use it. Also I have only attached onloadSound event to only the

I converted .wave and .mp3 files to .ogg or .mp3 with lower bit-rate with this cool tool: FormatFactory


The external functions

By now we should have two successfully loaded sounds, all we have to do now is create the functions that actually play them.


this.playSound = function(id,repeat,volume){
        id = this.registeredSounds[id];
        var instance = createjs.Sound.play(id);
        if(volume === undefined || volume === null){
            instance.volume = 0.1;
        }
        else{
            instance.volume = volume;
        }
        if(repeat===true){
            instance.addEventListener("complete", repeat);
        }
    }
    
    function repeat(){
      
        var id = this.registeredSounds["bg"];
        var instance = createjs.Sound.play(id);
        instance.volume = 0.1;
    
    }
    
    this.stopSound = function(id){
        createjs.Sound.stop(id);
    }

These functions here help us control the sounds whenever we want, we can either play/stop/or repeat a sound (the background sound) on demand. In my game the first “explosion like” sound is played when the player fires a missile.


_sound.playSound("track_T0Shot",false,0.1);

I hope it helps and if you have any questions feel free to comment below.


The complete sounds class


function sounds() {

    var $this = this;

    ///////////////////

    this.config = new Array();
    this.registeredSounds = new Array();
    var onLoad;
    checkSupport();

    function checkSupport() {
        if (!createjs.Sound.initializeDefaultPlugins()) {
            return false;
        }
    }

    this.preloadSound = function (path, track, track2, identifier, onLoad) {

        console.log(path + track + "|" + path + track2);
        var id = ("track_" + identifier);
        var manifest = [
            {
                id: id,
                src: path + track + "|" + path + track2
        }
        ];

        createjs.Sound.registerSound({
            id: id,
            src: path + track
        });
        createjs.Sound.registerSound({
            id: id,
            src: path + track2
        });

        onLoad = id;
        this.registeredSounds["track_" + identifier] = manifest[0].id;
        if (identifier === "bg") {
            createjs.Sound.addEventListener("fileload", onloadSound);
        }

        return manifest[0].id;
    }

    function onloadSound(e) {
        console.log(e);
        var trackID = e.currentTarget.id;
        createjs.Sound.removeAllEventListeners();

        var id = $this.registeredSounds[trackID];

        $.event.trigger({
            type: "soundReady",
            message: "bg sound is ready",
            time: new Date()
        });

    }

    this.playSound = function (id, repeat, volume) {
        id = this.registeredSounds[id];
        var instance = createjs.Sound.play(id);
        if (volume === undefined || volume === null) {
            instance.volume = 0.1;
        } else {
            instance.volume = volume;
        }
        if (repeat === true) {
            instance.addEventListener("complete", repeat);
        }
    }

    function repeat() {

        var id = this.registeredSounds["bg"];
        var instance = createjs.Sound.play(id);
        instance.volume = 0.1;

    }

    this.stopSound = function (id) {
        createjs.Sound.stop(id);
    }

    return this;
};

You can view an example here: SoundJS class example

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin
Tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *