如何计算HTMLAudio播放了多少次?

时间:2019-05-04 14:42:47

标签: javascript html5 html5-audio

我试图通过添加'audioPlayer'事件并使用ended属性返回一个HTML5音频对象(played)播放次数,来计算Timesrange对象。不过,这种方法只能奏效
好的,直到第一个完整侦听,即结束时,我得到一个Timesrange对象,其中包含所有部分侦听。对于进一步的收听,它只是“忘记”了第一次收听。

这是我的代码

const audioPlayer = document.getElementById('soundPlayer');
audioPlayer.addEventListener(
    'ended',
    function() {
      const timesPlayed = audioPlayer.played;
      let totalTimePlayed = 0;
      for (let i = 0; i < timesPlayed.length; i += 1) {
        totalTimePlayed += timesPlayed.end(i) - timesPlayed.start(i);
      }
      const ratioPlayed = totalTimePlayed / audioPlayer.duration;
    },
    true
  ); 

第二个问题是:如果用户在播放音频时离开页面(即未结束),如何强制ended事件? (此实验是一个多页的Web应用程序“调查”,每页中都有HTML5音频元素,用户可以收听该HTML5音频元素,然后按按钮进入下一页。

我正在尝试使用onbeforeunload,但无法触发“结束”事件。

function preventNavigatingAway() {
  window.onbeforeunload = function() {
    $('#soundPlayer').trigger('ended');
  };
}

其他注释:我不确定调用事件的顺序是否正确,所以这是我的完整代码:

function initAudio(audioPlayer) {

  audioPlayer.addEventListener(
    'ended',
    function() {
      const ratioPlayedInput = $("input:text[name='input-ratioPlayed']").val() || '0';
      let ratioPlayed = parseFloat(ratioPlayedInput);
      let timesPlayed = $("input:text[name='input-timesPlayed']").val();
      timesPlayed = parseInt(timesPlayed, 10) || 0;
      const currTimesPlayed = audioPlayer.played;
      let totalTimePlayed = 0;
      for (let i = 0; i < currTimesPlayed.length; i += 1) {
        totalTimePlayed += currTimesPlayed.end(i) - currTimesPlayed.start(i);
      }
      ratioPlayed += totalTimePlayed / audioPlayer.duration;
      ratioPlayed = parseFloat(ratioPlayed.toFixed(2));
      timesPlayed += currTimesPlayed.length;

      $("input:text[name='input-ratioPlayed']").val(ratioPlayed);
      $("input:text[name='input-timesPlayed']").val(timesPlayed);
    },
    true
  );
  return true;
}

function preventNavigatingAway() {
  console.log('preventNavigatingAway');
  window.onbeforeunload = function() {
    $('#soundPlayer').trigger('ended');
    console.log('in window.beforeunload()');
  };
}

document.addEventListener('DOMContentLoaded', function() {
  console.log('DOMContentLoaded!');
  const audioPlayer = document.getElementById('soundPlayer');
  initAudio(audioPlayer);
  preventNavigatingAway();
});

0 个答案:

没有答案