Playing multiple sounds using variables in howler.js

175 Views Asked by At

I am a beginner developer.

I tried to play multiple sound sources using howler.js. I thought find a simpler way to write it using variables.

source:

    var sound1 = new Howl({src: ['sound01.mp3']}),
        sound2 = new Howl({src: ['sound02.mp3']}),
        sound3 = new Howl({src: ['sound03.mp3']});

I want to play:

    $musicbox.eq(0).on('click', function(){
      sound1.play()
    }); 

    $musicbox.eq(1).on('click', function(){
      sound2.play()
    });    

    $musicbox.eq(2).on('click', function(){
      sound3.play()
    });    

so I tried to use variable...

    $musicbox.on('click', function(){
      
      var i = $(this).index();
      var sound = ["sound" + i]
      
      sound.play()
    }); 

I've tried several writing methods, but I keep failing. Is it impossible to create variables in howler.js? or just I write it wrong?

2

There are 2 best solutions below

2
Hasan Raza On BEST ANSWER
<div class="musicbox">Sound 1</div>
<div class="musicbox">Sound 2</div>
<div class="musicbox">Sound 3</div>


<script>
  var sounds = [
    new Howl({ src: ['sound1.mp3'] }),
    new Howl({ src: ['sound2.mp3'] }),
    new Howl({ src: ['sound3.mp3'] })
  ];

  $('.musicbox').on('click', function () {
    var i = $('.musicbox').index(this); 
    sounds[i].play(); 
  });
</script>
0
Roko C. Buljan On

You can achieve the desired using the data-* attribute in your HTML in order to store the key of the sound you want to play from your sounds Object:

<button type="button" data-sound="snare">Snare</button>
<button type="button" data-sound="kick">Kick</button>

then in JS (jQuery) all you need is:

const sounds = {
  snare: new Howl({src: ["sound01.mp3"], preload: true}),
  kick: new Howl({src: ["sound02.mp3"], preload: true}),
};

$("[data-sound]").on("click", function() {
  sounds[$(this).data("sound")].play();
});

or without the need of jQuery (in pure JavaScript):

const sounds = {
  snare: new Howl({src: ["sound01.mp3"], preload: true}),
  kick: new Howl({src: ["sound02.mp3"], preload: true}),
};

document.querySelectorAll("[data-sound]").forEach(elBtn => {
  elBtn.addEventListener("click", () => {
    sounds[elBtn.dataset.sound].play();
  });
});

this way, instead of guessing the array index to play you can be more descriptive in your code as well. Say you want to play the kick sound programmatically, you just use:

sounds.kick.play();
// or like
// sounds["kick"].play();