how to detect end of audio file using jquery and html5

后端 未结 3 941
别跟我提以往
别跟我提以往 2021-01-02 21:19

I\'ve got this jquery code and html to work OK for an English language training site.

$(document).ready(function() {
  $(\"p\").hover(
    function() {
             


        
相关标签:
3条回答
  • 2021-01-02 21:28
    var myAudio = new Audio('someSound.ogg'); 
    myAudio.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);
    myAudio.play();
    

    This Worked for jquery audio.

    0 讨论(0)
  • 2021-01-02 21:29
     ***var audioElement = null;***     
    
     $("p").click(function (event) {
    
        ***if (audioElement) {
            audioElement.pause();
         }***
    
    var element = $(this);
    var elementID = event.target.id;
    var oggVar = (elementID +".ogg");   
    audioElement = document.createElement('audio');
    audioElement.setAttribute('src', oggVar); 
    audioElement.load();
    audioElement.addEventListener("load", function() { 
        audioElement.play(); 
    }, true);
    audioElement.play();    
    
     }); 
    
    0 讨论(0)
  • 2021-01-02 21:37

    You can add event listeners for the ended and playing events. Also, why creating a audio tag via javascript? I would just create an empty hidden audio tag:

    <audio id='myAudio' autoplay='autoplay'></audio>
    

    You have two options:

    • disable/enable the button/link when audio is playing/stopped (preferred imho)
    • ignore clicks when already playing

    Then add two eventlisteners to it:

    var playing = false;
    
    $('#myAudio').on('playing', function() {
       playing = true;
       // disable button/link
    });
    $('#myAudio').on('ended', function() {
       playing = false;
       // enable button/link
    });
    
    $("p").click(function (event) {
       if(!playing) {
          var element = $(this);
          var elementID = event.target.id;
          var oggVar = (elementID +".ogg");   
          var audioElement = $('#myAudio')[0];
          audioElement.setAttribute('src', oggVar); 
          audioElement.play();
       }
    
    });
    
    0 讨论(0)
提交回复
热议问题