html5 play audio loop 4x then stop

后端 未结 5 2241
既然无缘
既然无缘 2020-12-12 03:14

Hi I need to loop audio file a certain number of times ie 4, I have the sound file looping correctly, code below. ? how to stop loop after 4x, many thanks P

         


        
5条回答
  •  天涯浪人
    2020-12-12 03:56

    Throw in a simple if statement with a counter like so:

    UPDATED:

    $('#play_audio').click(function () {
                var audio = document.createElement("audio");
                audio.src = "files/windows%20default.mp3";
    
                audio.addEventListener('ended', function () {
    
                    var repeat = 0;
    
                    // Wait 500 milliseconds before next loop  
                    setTimeout(function () {
                          if repeat < 3 {
                               var repeat = repeat + 1;
                               audio.play();
                          }
                          else {
                               return done;                
                          }
                    }, 500);
    
                }, false);
    
          audio.play();
    });
    

    SECOND UPDATE:

    $('#play_audio').click(function () {
            var audio = document.createElement("audio");
            audio.src = "files/windows%20default.mp3";        
    
            delay(500).audio.play();
            delay(1000).audio.play();
            delay(1500).audio.play();
            delay(2000).audio.play();
    });
    

    It's not scalable from a programming standpoint, but if you're trying to just solve this one problem this one time it's a viable workaround.

    I'm sure if I had more time and we could do a chat perhaps I could get the loop code working, but try this and let me know if it does the trick.

提交回复
热议问题