【问题标题】:Play / Pause audio file with JavaScript / jquery by fetching .attr通过获取 .attr 使用 JavaScript/jquery 播放/暂停音频文件
【发布时间】:2015-09-20 09:18:13
【问题描述】:

按下播放时,文件 mp3 应播放,再次单击时 mp3 应暂停。目标是从'key'中获取文件名,然后在javascript/jquery中添加目录+ .mp3。

它正在播放但没有暂停。

<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
<script>
  $(".play").click(function(){
    var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
    if (audio.paused) {
      audio.play();
    }   
    else {
      audio.pause();
    }
    $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
  });
</script>

【问题讨论】:

    标签: javascript jquery audio


    【解决方案1】:

    原因是,每次点击它都会执行这个:

    var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
    

    所以你需要做的是,在前面添加一个条件:

    var audio;
    if (typeof audio == "undefined")
      audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
    

    您的完整代码是:

    <span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
    <script>
      var audio;
      $(".play").click(function(){
        if (typeof audio == "undefined")
          audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
        if (audio.paused) {
          audio.play();
        }   
        else {
          audio.pause();
        }
        $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
      });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多