首页 > 解决方案 > Track the total time the HTMLAudio was playing

问题描述

How could I track for how long was the HTMLAudio playing in total?

What I tried to do is to run the following function each time an audio started to play or paused:

let totalTimeInSeconds = 0;
let intervalId = null;

const startedToPlay = function() {
    intervalId = setInterval(function() { ++totalTimeInSeconds; }, 1000);
};
const pausedPlaying = function() {
    clearInterval(intervalId);
};

But I am getting a little bit of a difference. The difference is +-20 seconds.

So, what is a better way to do this?

In order to avoid the x-y problem: I need this to trigger my own events once the audio played for more than a specified amount of time in total (that means that we can rewind the audio back and forth, but still we are only interested in total time listened and not the length of the audio listened).

Thank you.

标签: javascripthtmlaudiotime

解决方案


我解决这个问题的方法是在他们开始播放时简单地设置一个超时,并在他们暂停时清除超时,并更新仅在暂停时剩余的总时间。

就像是:

const SECOND = 1000;
let timeLeft = 5 * SECOND;
let startTime = null;
let timeout = null;
let div = document.getElementById('timer')
let toggle = document.getElementById('toggle');
let playing = false;
toggle.addEventListener('click', () => {
    if (playing) {
        pausedPlaying();
    } else {
        startedToPlay();
    }
    playing = !playing;
});

const startedToPlay = function() {
    startTime = (new Date()).getTime();
    timeout = setTimeout(() => alert(), timeLeft);
};

const pausedPlaying = function() {
    clearTimeout(timeout);
    timeLeft -= (new Date()).getTime() - startTime;
    startTime = null;
};

setInterval(() => div.textContent = startTime ? (timeLeft - ((new Date()).getTime() - startTime)) : timeLeft);
<div id="timer">5</div>

<button id="toggle">Start/Stop</button>

请注意,底部的时间间隔仅用于更新显示的剩余时间。


推荐阅读