【问题标题】:How to play sound when the current time equals to specific time当前时间等于特定时间时如何播放声音
【发布时间】:2013-04-19 01:05:11
【问题描述】:

在我的网页中,我想在当前时间等于 时播放声音,例如下午 5:00。

我所做的是:

<script type='text/css'>
var d = new Date();
var m = d.getMinutes();
var h = d.getHours();
if (h == 17 && m == 00){
document.write = "<embed src =\'notify.mp3\' hidden=\'true\' autostart=\'true\' loop=\'true\'></embed>";
}
</script>

我寻找了一个播放声音的特定功能,我发现document.write 不起作用并且没有意义。

任何建议我应该怎么做

【问题讨论】:

标签: javascript html


【解决方案1】:

我假设您正在尝试创建类似警报的功能。这就是我要做的:

var delay = 60000; // in milliseconds, check every minute
var intervalId = setInterval("playWhenReady()", delay);

function playWhenReady()
{
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes(); 

    if (h === 17 && m === 00)
    {
        playSound('notify.mp3');
        clearInterval(intervalId);              
    }
}

function playSound(soundFile)
{
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', soundFile);
    audioElement.play();
}

【讨论】:

    【解决方案2】:

    在 JS 中试试这个:

     <script>
    var d = new Date();
    var m = d.getMinutes();
    var h = d.getHours();
    if (h == 17 && m == 00){
          var sound = document.getElementById(sound1);
          sound.Play();
    }
    </script>
    

    别忘了在 HTML 中添加这个

    <embed src="notify.mp3" autostart="false" width="0" height="0" id="sound1"
    enablejavascript="true">
    

    【讨论】:

    • This浏览器处于非活动状态或被用户最小化时播放声音。希望对某人有所帮助。
    【解决方案3】:

    试试这样的。

    document.getElementById("dummy").innerHTML= "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
    

    使用元素

    标签定义了一个外部(非 HTML)内容的容器。以下代码片段应该播放嵌入在网页中的 MP3 文件:

    例子

    <embed height="50" width="100" src="horse.mp3">
    

    或者试试

    尝试使用这个修改后的函数 play()

    function play() 
    {
      var embed=document.createElement('object');
      embed.setAttribute('type','audio/wav');
      embed.setAttribute('data', 'c:\test.wav');
      embed.setAttribute('autostart', true);
      document.getElementsByTagName('body')[0].appendChild(embed);
    }
    

    参考:http://www.w3schools.com/html/html_sounds.asp

    http://webdesign.about.com/od/sound/a/play_sound_oncl.htm

    Playing sound with JavaScript

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多