3

I have looked all over but nothing so far. I'm stuck.

I have an html audio element and I want to control it with a div. When I click on the div it plays the music, but what I need is when I click on it again to stop playing but don't know how.

This is audio tag.

<audio class="audioplayer" preload="none" style="display: none;" >
   <source  src="audio/ocean.mp3" type="audio/mpeg">
</audio>

And this is jquery controlling the play with the div (#ocean).

$('#ocean').click(function() {
          if ('.audioDemo'.paused == false) {
              $(".audioDemo").trigger('pause');
          } else {
              $(".audioDemo").trigger('play');
          }
        });

        function stopAudio(){
            $(".audioDemo").trigger('pause'); //pause playing
            $(".audioDemo").prop("currentTime",0); //set play time to 0
        }

I have wrote stop function and it works but only if I hock it up on another div. I have tried with that .paused but its not working.

How can I use same div as play and stop?

THX

2 Answers2

4

Strings don't have pause property, so check '.audioDemo'.pause won't work. You need to check plain HTMLAudioElement object pause property.

So with the help of jQuery you select $(".audioDemo") jQuery object collection, and from there you get raw HTML element as the first element of this collection:

$('#ocean').click(function () {
    if ($(".audioDemo")[0].paused == false) {
        $(".audioDemo").trigger('pause');
    } else {
        $(".audioDemo").trigger('play');
    }
});

Or a little bit optimized code:

$('#ocean').click(function () {
    var $audioObj = $(".audioDemo");
    $audioObj.trigger(!$audioObj[0].paused ? 'pause' : 'play');
});

function stopAudio() {
    $(".audioDemo").trigger('pause').prop("currentTime", 0);
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
2

Consider this following code:

$('#ocean').click(function () {
    if ($(".audioDemo").get(0).paused == false) {
        $(".audioDemo").trigger('pause');
    } else {
        $(".audioDemo").trigger('play');
    }
});

You can use following methods while selecting element with index:

$("#element")[index]
$("#element").get(index)
$("#element").eq(index)

Demonstration

Note: '.audioDemo'.pause is incorrect for checking audio is paused or not. Means you can't access audio Object like this. If you want to do so use $('element').


Stop functionality added:

$('#stop').click(function(){
    $(".audioDemo").trigger('pause'); //pause playing
    $(".audioDemo").prop("currentTime",0); //set play time to 0
});

Updated Demo

Manwal
  • 23,450
  • 12
  • 63
  • 93
  • `.eq(index)`'s purpose is to select an element by index while retaining the attached jQuery methods and it cannot be used to get the native `audio`element. – SeinopSys Apr 08 '15 at 21:37