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
Answers
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 yoursounds
Object:then in JS (jQuery) all you need is:
or without the need of jQuery (in pure JavaScript):
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: