How to play sound when the current time equals to

2020-06-17 06:27发布

In my web page, I would like to play sound when the current time equals to , for example, 5:00 pm.

What I did is:

<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>

I looked for a specific function that plays the sound and I found document.write which doesn't work and doesn't make sense.

Any suggestion what I should do

3条回答
The star\"
2楼-- · 2020-06-17 06:37

Try something like this.

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

Using The Element

The tag defines a container for external (non-HTML) content. The following code fragment should play an MP3 file embedded in a web page:

Example

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

Or try

Try using this revised version of the function 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);
}

Refence: http://www.w3schools.com/html/html_sounds.asp

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

Playing sound with JavaScript

查看更多
冷血范
3楼-- · 2020-06-17 06:38

Try this in 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>

Dont forget to add this in HTML

<embed src="notify.mp3" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">
查看更多
贪生不怕死
4楼-- · 2020-06-17 06:43

I am assuming you are trying to create an alarm-like functionality. Here's what I would do:

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();
}
查看更多
登录 后发表回答