jqueryvariablesaudiohowler.js

Playing multiple sounds using variables in howler.js


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?


Solution

  • <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>