在手机上反复播放HTML声音会有奇怪的行为



我有一个js程序,通过计时器使声音反复播放,并在我的计算机上工作得很好,但是,当我试图在我的手机(iPhone 13)或平板电脑(iPad air 4)上使用它时,它不起作用。声音要么晚了,要么根本不播放。我还注意到,如果我在程序运行时改变手机的系统音量(通过手机侧面的物理按钮),音量条会出现滞后和跳跃,而不是平稳地增加或减少。

设置允许声音在ios上播放(因为它们需要用户交互)

var click1 = new Audio('../audio/click1.mp3');
click1.preload = "auto";
enterBtn.addEventListener('click', () => {
//...code
click1.volume = 0;
click1.play();
click1.pause();
click1.currentTime = 0;
click1.volume = 1;
});

计时器

调用时运行的代码
function playClick() {
click1.load();
click1.play();
click1.currentTime = 0;
//...code
}

我从堆栈溢出中获取的定时器代码

function Timer(callback, timeInterval, options) {
this.timeInterval = timeInterval;

this.start = () => {
this.expected = Date.now() + this.timeInterval;
this.theTimeout = null;
if (options.immediate) {
callback();
}
this.timeout = setTimeout(this.round, this.timeInterval);
console.log('Timer Started');
}
this.stop = () => {
clearTimeout(this.timeout);
}
this.round = () => {
var drift = Date.now() - this.expected;
if (drift > this.timeInterval) {
if (options.errorCallback) {
options.errorCallback();
}
}
callback();
this.expected += this.timeInterval;
this.timeout = setTimeout(this.round, Math.max(0,this.timeInterval - drift));
}
}
export default Timer;

如何使用setInterval代替定时器?https://developer.mozilla.org/en-US/docs/Web/API/setInterval

最新更新