Reputation: 401
I am trying to make a music player with audio visualization. I want it to function as when I click on the name of track then that track should start playing
<script src="main.js"> </script>
<script src="/circular-audio-wave.min.js"></script>
<script>
var sel2= 'audio/audio3.mp3',
sel1 = '';
$( "li" ).click(function() {
sel1 = ($(this).data('val'));
sel2 = 'audio/' + sel1;
console.log(sel2);
});
let wave = new CircularAudioWave(document.getElementById('chart-container'));
wave.loadAudio(sel2);
</script>
I want that sel2 value is sent outside the jQuery function so that it can be used by 'wave.loadAudio(sel2);'. As on running this script I am getting only the 'audio/audio3.mp3' playing as I have given this value to variable earlier. I want that it sets the new value of sel2 (whichever I click and then pass it to wave.loadAudio(sel2)) so that every time on clicking new track I get that track playing.
Upvotes: 0
Views: 93
Reputation: 1725
You don't really understand how callback functions works in javascript, which are asynchronous side of javascript. Your wave.loadAudio(sel2)
will always get audio/audio3.mp3
because is loaded before your click function. Look on the simple example:
console.log('First');
setTimeout(function(){
console.log('Second')
},0);
console.log('Third');
If you run this script you will see: 'First', 'Third', 'Second', because callback function is added to the Callback queue
, and when call stack
is empty this function is realised, in this way callback function can be using as non-blocking. So in your example you should add wave.loadAudio(sel2)
to the body click function:
var sel2= 'audio/audio3.mp3';
let wave = new CircularAudioWave(document.getElementById('chart-container'));
sel1 = '';
$( "li" ).click(function() {
sel1 = ($(this).data('val'));
sel2 = 'audio/' + sel1;
wave.loadAudio(sel2);
});
Btw your code has more errors. Try to use default parameters, arrow functions, don't declare global variables (sel1), avoid using var
, sel1 should be declared inside click function not outside.
Upvotes: 2