Javascript 延迟后是否播放音频标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11973673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:54:03  来源:igfitidea点击:

Have audio tag play after a delay?

javascriptjqueryhtmlhtml5-audio

提问by Charlie

I'm playing an MP3 using the <audio>tag in HTML5.

我正在使用<audio>HTML5 中的标签播放 MP3 。

<audio controls="controls" autoplay="autoplay">
  <source src="song.mp3" type="audio/mp3" />
</audio>

This works fine, but I am wondering how I can put a delay in before the song starts to autoplay? I know there's not a delayattribute, but I'm thinking it could be accomplished via javascript?

这工作正常,但我想知道如何在歌曲开始自动播放之前延迟?我知道没有delay属性,但我认为它可以通过 javascript 完成?

回答by Ian Routledge

Try this, really simple but you should move the JS outside the markup...

试试这个,真的很简单,但你应该将 JS 移到标记之外......

<audio controls="controls" onloadeddata="var audioPlayer = this; setTimeout(function() { audioPlayer.play(); }, 8000)">
    <source src="Kalimba.mp3" type="audio/mp3" />
</audio>

回答by Philip Kirkbride

Javascript only method:

仅 Javascript 方法:

var sound = document.createElement('audio')
sound.id = 'audio'
sound.controls = 'controls'
sound.src = 'http://a.tumblr.com/tumblr_leltkjNwWL1qf32t9o1.mp3'
sound.type = 'audio/mp3'
document.body.appendChild(sound)

function playAudio() {
  document.getElementById('audio').play();
}

setTimeout("playAudio()", 3000);

回答by Lil' Bits

Try this:

尝试这个:

HTML:

HTML:

<div id='audio'>This will be replaced with an audio tag</div>?

jQuery:?

jQuery:?

$(document).ready(?function (){
    $("#audio").stop("true").delay('2000').queue(function() { 
      $(this).html('<audio controls="controls" autoplay="autoplay"><source src="song.mp3" type="audio/mp3" /></audio>');
    });
});?

All together would be:

所有在一起将是:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    </head>
    <body>
        <div id='audio'>This will be replaced with an audio tag</div>
        <script type='text/javascript'>
            $(document).ready(function (){
                $("#audio").stop("true").delay('2000').queue(function() { 
                    $(this).html('<audio controls="controls" autoplay="autoplay"><source src="song.mp3" type="audio/mp3" /></audio>');
                });
            });
        </script>
    </body>
</html>

You can use .delay()to delay a process in jQuery. The time is in milliseconds, so 2000 = 2 seconds.

您可以使用.delay()jQuery 来延迟进程。时间以毫秒为单位,所以 2000 = 2 秒。