user3549735
user3549735

Reputation: 35

Play multiple audio files with one click event howler js

Wordpress website. Scripts enqueued etc. I was able to get a single audio file to play without the array.

After using this though...

(function( $ ) {
'use strict';

jQuery(window).load(function() {
    var sound_files = {
            sound1 : new Howl({
                src: ['/synthv2.mp3'],
                loop: true
            }),
            sound2 : new Howl({
                src: ['/synthv2.mp3'],
                loop: true
            }),
            sound3 : new Howl({
                src: ['/synthv2.mp3'],
                loop: true
            })
        };
    var play_button = $('#play-button'),
        pause_button = $('#pause-button'),
        shift_preset = $('#preset-changer'),

    play_button.click(function() {
        sound_files.play();
    });
});

})(jQuery);

I consistently get sound_files.play is not a function errors.

How can I trigger sound1, sound2, and sound3 all at the same time with a single button click?

Upvotes: 2

Views: 2934

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

or you could...

    var sound_files = {
        sound1 : new Howl({
            src: ['/synthv2.mp3'],
            loop: true
        }),
        sound2 : new Howl({
            src: ['/synthv2.mp3'],
            loop: true
        }),
        sound3 : new Howl({
            src: ['/synthv2.mp3'],
            loop: true
        }),
        play: function(){
            this.sound1.play();
            this.sound2.play();
            this.sound3.play();
        }
    };

Upvotes: 1

Blue
Blue

Reputation: 22911

sound_files is an object, so you can't simply call .play() on them.

You would need to loop through them, and play them all:

for (var prop in sound_files) {
    // skip loop if the property is from prototype
    if(!sound_files.hasOwnProperty(prop)) continue;

    sound_files[prop].play();
});

Upvotes: 1

Related Questions