javascripthowler.js

How to chain sounds on howler.js


I need to play some sounds in howler.js the thing is that I don't know how to chain it.

For example, at string BCG

would need to play b.ogg then c.ogg and finally g.ogg

If I just use (after loading):

sound.play('b');
sound.play('c');
sound.play('g');

All of them start and overlap which isn't what I need.

I see there's a onend property, however can't figure out how to use it properly.

Regards.


Solution

  • You could create a function playString(yourString) that will read each character and dynamically set the onend property of your sound. The following example should play B C G A C:

    var sound = new Howl({
        urls: ['http://shrt.tf/abcdefg.mp3'],
        volume: 1,
        sprite: {
            a: [0, 600],
            b: [700, 500],
            c: [1200, 600],
            d: [1900, 500],
            e: [2400, 500],
            f: [2900, 500],
            g: [3400, 500],
        }
    });
    
    Howl.prototype.playString = function(str){
        if(str.length>1){
            this._onend[0] = function(){this.playString(str.substring(1,str.length));};
        } else {
            this._onend[0] = function(){};
        }
        if(str.length>0){
            this.play(str.substring(0,1));
        }
    };
    
    sound.playString('bcgac');
    <script src="http://shrt.tf/howler.js"></script>

    Note that you could also tweak this function to work when a character is not in the sprite, or to use an array of names instead of a string.