Have audio tag play after a delay?

早过忘川 提交于 2019-11-30 15:00:50

问题


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

<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 delay attribute, but I'm thinking it could be accomplished via javascript?


回答1:


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

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



回答2:


Javascript only method:

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



回答3:


Try this:

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

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.



来源:https://stackoverflow.com/questions/11973673/have-audio-tag-play-after-a-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!