only second audio plays on array

前端 未结 1 1253
-上瘾入骨i
-上瘾入骨i 2021-01-24 02:37

I declared ar array variable and added my two audios inside but when I hit .play only second element into array plays. any solutions ?

         


        
相关标签:
1条回答
  • 2021-01-24 03:08

    You are misunderstanding the meaning of the comma operator in javascript arrays (in that scenario specifically):

    ar[0 , 1]
    

    is equivalent to:

    ar[1]
    

    So, only the last element is played, because in fact you are selecting binding to the src property of the audio object the last element of the array, which is "songs/example2.mp3" or, really, trench03.

    If you want to play both, you need to first create an Audio object for each of them, set the src attribute and loop them on click, by executing the play method of each:

    var trench01 = 'songs/example1.m4a';
    var trench03 = 'songs/example2.mp3';
    var ar = [trench01, trench03];
    var tracks = ar.map((trench) => {
       var audio = new Audio();
       audio.src = trench;
       return audio;
    });
    $('.play').click(function(){
        tracks.forEach(track => track.play());
    })
    
    0 讨论(0)
提交回复
热议问题