如何使此音频文件仅在列出的时间播放,而不是在之后的任何时间播放?

时间:2016-02-01 21:36:07

标签: javascript audio timed

以下是我从这个网站获得的代码。谢谢。但每次加载页面时,它会在16:24之后的任何时间播放音频文件。有办法防止这种情况吗?

var now = new Date(); var audio1 = new Audio(' one_minute_remaining-2.mp3');

var millisTill10 = new Date(now.getFullYear(),now.getMonth(),now.getDate(),16,24,00,0)-now;

if(millisTill10< 0)

{      millisTill10 + = 1000; //上午10点之后,明天上午10点。

} setTimeout(function(){audio1.play()},millisTill10);

1 个答案:

答案 0 :(得分:0)

var now = new Date(); 
var audio1 = new Audio('one_minute_remaining-2.mp3');

//Change the hours, minutes, seconds to the time you want it to play
var timeIWantItToPlay = new Date( 
    now.getFullYear(), 
    now.getMonth(), 
    now.getDate(),
    16, 24, 00, 0
);

//This is the "exactness" of the time. So if it's within 1 second, it will play
var leeway = 1000;

if ( ( now.getTime() > timeIWantItToPlay.getTime() - leeway ) && ( now.getTime() < timeIWantItToPlay.getTime() + leeway )
{
     audio1.play();
}