How to play sound tags after a delay?

I play MP3 using the <audio> in HTML5.

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

This works great, but I wonder how I can delay before the song starts auto play? I know there is no delay attribute there, but I think it can be done using javascript?

+8
javascript jquery html html5 html5-audio
source share
3 answers

Try this, very simple, but you have to move JS out of the markup ...

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

Javascript method only:

 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); 
+7
source share

Try the following:

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>'); }); });โ€‹ 

Together:

 <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 the process in jQuery. Time in milliseconds, so 2000 = 2 seconds.

+2
source share

All Articles