Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect end of audio file using jquery and html5

Tags:

html

jquery

audio

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

$(document).ready(function() {
  $("p").hover(
    function() {
      $(this).css({"color": "purple", "font-weight" : "bolder"});
    },
    function() {
      $(this).css({"color": "black", "font-weight" : ""});
    }
  ); 
  $("p").click(function (event) {
    var element = $(this);
    var elementID = event.target.id;
    var oggVar = (elementID +".ogg");   
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', oggVar); 
    audioElement.load();
    audioElement.addEventListener("load", function() { 
        audioElement.play(); 
    }, true);
    audioElement.play();    
  }); 
});

<div>
  <p id="one"> this is the first paragraph</p>
....   
  <p id="four"> this is the fourth paragraph</p> 
....   
</div>

the problem is that if text is clicked on while an audio file is playing (or double clicked) then the second file (or the same file) starts playing. So I end up with two files playing simultaneously. I need to prevent this. I think that the 'ended' event is relevant but, despite looking some examples, I can't see quite how to detect if a file is playing and wait until it's finished before allowing a second file to start (or even prevent it from playing at all). Any help would be much appreciated :)

like image 635
RoyS Avatar asked Mar 23 '13 11:03

RoyS


People also ask

How do I stop audio from playing HTML?

Audio pause() Method The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).

How check audio is playing or not in JavaScript?

The Audio tag has a paused property. If it is not paused, then it's playing.


1 Answers

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();
   }

});
like image 197
asgoth Avatar answered Nov 09 '22 17:11

asgoth