HTML5中音频开始和音频播放(暂停后)之间的区别

问题描述 投票:0回答:1

如何在音频/视频开始时添加侦听器?

我可以这样做:

$audio.on("play", function() {
    console.log("audio played");
});

其中$ audio是表示单个DOM音频元素的jQuery对象。

但是当我们继续播放视频时,它也会运行。我希望它仅在开始时运行。

我可以做到的一种方法是:

$audio.on("play", function() {
  if(this.currentTime === 0) {
      console.log("audio started);
  }
});

但是在开始播放/暂停音频时,它将运行多次。

还有其他更好的方法吗?侦听器仅应在音频开始和重放音频上工作,当用户手动将搜索栏拖动到源的开始时,不是

javascript jquery html html5-video html5-audio
1个回答
0
投票

将标志存储到目标元素的data-*属性中:

const $audio = $('.audio');
$audio.on("play", function() {
  
  if ($(this).data('once-played')) return; // Do nothing if data exists.
  
  // Your code here
  console.log("Audio started for the first time");

  // Finally, add a flag.
  $(this).data('once-played', true);
});
<audio class="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay controls loop></audio>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.