javascript - 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.
解决方案
我解决这个问题的方法是在他们开始播放时简单地设置一个超时,并在他们暂停时清除超时,并更新仅在暂停时剩余的总时间。
就像是:
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>
请注意,底部的时间间隔仅用于更新显示的剩余时间。
推荐阅读
- javascript - 不使用从 fetch 调用返回的数据设置状态
- python - Kivy Python - 使用 kivy.utils.rgba 的颜色错误
- sql - 查询考试成绩计算
- javascript - 如何避免javascript中的小数错误?
- django - UpdateView 创建新对象而不是更改原始对象
- webpack - webpack string 用 jest 替换加载器替代方案
- mysql - 在 MySQL 5.6 中使用 GROUP BY 模拟 LAG
- java - 以编程方式将鼠标单击注入鼠标 I/O 流
- browser - 无法发布 Edge 浏览器扩展:包接受验证错误
- javascript - 无法循环从 api 返回的数据