gpt4 book ai didi

javascript - 当它应该是一个定时事件时,音频声音正在加载

转载 作者:行者123 更新时间:2023-11-28 02:15:28 25 4
gpt4 key购买 nike

音频设置为在特定时间播放,就像我主页背景中内置的闹钟一样。它在正确的时间播放。但是,由于某种原因,它也会在网页加载时播放。如果有人能弄清楚,我将非常感激,因为我一无所知。

var date = new Date(),
year = date.getFullYear(),
month = date.getMonth(),
weekday = date.getDay(),
day = date.getDate(),
time = date.getTime(),
timeout1 = new Date(year, month, day, 12, 15, 0, 0).getTime() - time,
timeout2 = new Date(year, month, day, 14, 30, 0, 0).getTime() - time,
timeout3 = new Date(year, month, day, 17, 0, 0, 0).getTime() - time,
timeout4 = new Date(year, month, day, 19, 0, 0, 0).getTime() - time,
timeout5 = new Date(year, month, day, 23, 45, 0, 0).getTime() - time,
mp3 = new Audio("audio/alarm.mp3"),
ogg = new Audio("audio/alarm.ogg"),
audio;

if (typeof mp3.canPlayType === "function" && mp3.canPlayType("audio/mpeg") !== "")
audio = mp3;
else if (typeof ogg.canPlayType === "function" && ogg.canPlayType("audio/ogg") !== "")
audio = ogg;

setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout1);
setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout2);
setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout3);
setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout4);
setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout5);

最佳答案

timeout1 是负值,因为它是在中午 12 点之后。至少在我的时区东部时间是这样。因此,您可能应该为正时间添加一个条件。

您可以将超时包含在 if 子句中,例如:

if(timout1 > 0){
setTimeout(function(){
if (weekday > 0 && weekday < 6) {
audio.play();
}
}, timeout1);
}

此外,我会对其进行重组,以限制您在每次超时时重写所有内容。

var date = new Date(),
year = date.getFullYear(),
month = date.getMonth(),
weekday = date.getDay(),
day = date.getDate(),
time = date.getTime(),
timeouts = [],
timeouts.push(new Date(year, month, day, 12, 15, 0, 0).getTime() - time),
timeouts.push(new Date(year, month, day, 14, 30, 0, 0).getTime() - time),
timeouts.push(new Date(year, month, day, 17, 0, 0, 0).getTime() - time),
timeouts.push(new Date(year, month, day, 19, 0, 0, 0).getTime() - time),
timeouts.push(new Date(year, month, day, 23, 45, 0, 0).getTime() - time),
mp3 = new Audio("audio/alarm.mp3"),
ogg = new Audio("audio/alarm.ogg"),
audio;

if (typeof mp3.canPlayType === "function" && mp3.canPlayType("audio/mpeg") !== "")
audio = mp3;
else if (typeof ogg.canPlayType === "function" && ogg.canPlayType("audio/ogg") !== "")
audio = ogg;

for(var i=0;i<timeouts.length;i++){
if(timeouts[i] > 0){
setTimeout(function(){
audio.play();
}, timeouts[i]);
}
}

编辑:更正了由于拼写错误造成的错误。

关于javascript - 当它应该是一个定时事件时,音频声音正在加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16467291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com