1

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

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);
4

1 回答 1

1

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]);
    }
}

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

于 2013-05-09T17:29:04.420 回答