2013-05-09 80 views
1

音頻設置爲在特定時間播放,就像內置於我主頁背景中的鬧鐘一樣。它在正確的時間播放。但是,由於某種原因,它也在加載網頁上播放。如果任何人都能弄明白,那將會非常感激,因爲我很無能。音頻聲音播放onload應該是一個定時事件

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); 
+0

添加一個'的console.log()'在每個超時的,看看哪一個是打 – Ibu 2013-05-09 17:29:11

+0

絕對是第一個這樣jasonmmiraglia是正確的,到目前爲止,只是搞清楚如何使它正時間 – stesab92 2013-05-09 17:34:39

回答

1

timeout1是一個負值,因爲它是在中午12點以後。至少在我的時區EST。所以你應該爲積極的時間添加條件。

你只需換一個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]); 
    } 
} 

編輯:更正錯誤,由於錯別字。

+0

多謝支持,幫了我很多。 – stesab92 2013-05-09 17:45:54