0

I have an audio element, I run it by clicking on the other element, and that element changes style while the sound is playing and back afterwords.

<audio preload="auto" id="axxx">
  <source type="audio/mpeg" src="sound/xxx.mp3"></source>
  <source type="audio/ogg" src="sound/xxx.ogg"></source>
  Not supported
</audio>

But for some elements, I have no audio, so I want to check, if the audio element was successfully loaded. I have tried to check the duration, but the condition is always false.

$("#lxxx").click(function () {
    if ($('#axxx').duration > 0) {
        $('#axxx').get(0).play();
        $('#lxxx').css("background-color", "orange");
    }
});
$('#axxx').on('ended', function () {
    $('#lxxx').removeAttr('style');
});

What is the way to ensure, if the audio was successfully loaded?

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
ojinmor
  • 133
  • 3
  • 10
  • possible duplicate of [How do you check if a HTML5 audio element is loaded?](http://stackoverflow.com/questions/8059434/how-do-you-check-if-a-html5-audio-element-is-loaded) and jQuery specific tutorial here: http://writings.whiteboard.is/introduction-to-html5-audio-in-js/ – Joe Jun 14 '13 at 09:58

1 Answers1

0

According to the links to the non-jquery answers, this solution is used - the main point is to use event 'canplay' and 'canplaythrough':

var axxxplay = false;
$("#lxxx").click(function () 
{
    if (axxxplay) 
    { 
        $('#axxx').get(0).play();
        $('#lxxx').css("background-color", "orange");
    }
});
$('#axxx').on('canplay canplaythrough', function() 
{    
    axxxplay = true;
});
ojinmor
  • 133
  • 3
  • 10