如何检测HTML5音频标签是否已被监听至少x秒?

dan*_*dan 10 audio html5

当用户收听音频元素超过5秒时,我想记录.如何使用HTML5检测到这一点?

Jus*_*ith 3

我将处理播放事件,然后在完成后使用 setTimeout 调用轨道。像这样的东西(伪代码):

    var timeHandler = null;

// if they stop listening, don't give them the alert
   myAudioElement.addEventListener('stop', function() {
     if (timeHandler) clearTimeout(timeHandle);
   });

// when they start to play, set an event to pop up 5 seconds later
    myAudioElement.addEventListener('play', function() {
        timeHandler = setTimeout(5000,function() {
          // here I would make some kind of ajax call to log the event
          alert("it's been 5 seconds!");
        });
Run Code Online (Sandbox Code Playgroud)

与往常一样,根据您的需求,这可能会变得更加复杂。您还可以使用 ontimeupdate 事件来跟踪播放头当前所在的位置。有关 html5 音频事件的参考,请查看此页面:

https://developer.mozilla.org/en/DOM/Media_events

祝你好运!