user3549735 user3549735 - 4 months ago 50
Javascript Question

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?

Answer

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();
});