延迟后播放音频标签吗?

时间:2012-08-15 16:58:54

标签: javascript jquery html html5 html5-audio

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

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

这很好用,但我想知道在歌曲开始自动播放之前我怎么能延迟?我知道没有delay属性,但我认为可以通过javascript完成?

3 个答案:

答案 0 :(得分:15)

试试这个,非常简单,但你应该把JS移到标记之外......

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

答案 1 :(得分:7)

仅限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);

答案 2 :(得分:2)

试试这个:

HTML:

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

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>');
    });
});​

一起将是:

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

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

相关问题