html5 audio player - jquery toggle click play/pause?

前端 未结 15 2253
南笙
南笙 2020-11-28 06:24

i wonder what i\'m doing wrong?

    $(\'.player_audio\').click(function() {
    if ($(\'.player_audio\').paused == false) {
        $(\'.player_audio\').paus         


        
相关标签:
15条回答
  • 2020-11-28 06:29

    You can call native methods trough trigger in jQuery. Just do this:

    $('.play').trigger("play");
    

    And the same for pause: $('.play').trigger("pause");

    EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");

    0 讨论(0)
  • 2020-11-28 06:29

    it might be nice toggling in one line of code:

    let video = $('video')[0];
    video[video.paused ? 'play' : 'pause']();

    0 讨论(0)
  • 2020-11-28 06:29

    The reason why your attempt didn't work out is, that you have used a class-selector, which returns a collection of elements, not an (=one!) element, which you need to access the players properties and methods. To make it work there's basically three ways, which have been mentioned, but just for an overview:

    Get the element – not a collection – by...

    • Iterating over the colllection and fetching the element with this (like in the accepted answer).

    • Using an id-selector, if available.

    • Getting the element of a collection, by fetching it, via its position in the collection by appending [0] to the selector, which returns the first element of the collection.

    0 讨论(0)
  • 2020-11-28 06:31

    If you want to play it, you should use

    $("#audio")[0].play();
    

    If you want to stop it, you should use

    $("#audio").stop();
    

    I don't know why, but it works!

    0 讨论(0)
  • 2020-11-28 06:32

    I'm not sure why, but I needed to use the old skool document.getElementById();

    <audio id="player" src="http://audio.micronemez.com:8000/micronemez-radio.ogg"> </audio>
    <a id="button" title="button">play sound</a>
    

    and the JS:

    $(document).ready(function() {
      var playing = false;
    
      $('a#button').click(function() {
          $(this).toggleClass("down");
    
          if (playing == false) {
              document.getElementById('player').play();
              playing = true;
              $(this).text("stop sound");
    
          } else {
            document.getElementById('player').pause();
            playing = false;
            $(this).text("restart sound");
          }
    
      });
    });
    

    Check out an example: http://jsfiddle.net/HY9ns/1/

    0 讨论(0)
  • 2020-11-28 06:33

    Try using Javascript. Its working for me

    Javascript:

    var myAudioTag = document.getElementById('player_video');
    myAudioTag.play();
    
    0 讨论(0)
提交回复
热议问题