Search code examples
javascripthtmlgoogle-chromeappcelerator

Adding a two second delay into background music


This is the code that I have written to play a music in the background. how can I add a two-second delay into it? this would give time for the images to fully load

<!DOCTYPE html>
<html>
<head>
<title>Animate</title>
<script type="text/javascript">
     var isChrome = /Chrome/.test(navigator.userAgent) && /Google 
Inc/.test(navigator.vendor);
        if(!isChrome){
  $('#iframeAudio').remove()
}
else{
 $('#playAudio').remove() //just to make sure that it will not have 2x audio 
in the background 
}
</script>
</head>
<body>
<iframe src="Happy Birthday Song.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe> 
<audio autoplay loop  id="playAudio">
  <source src="Happy Birthday Song.mp3">
</audio>
</body>
</html>

Solution

  • hi here is what I suggest you should do. First and foremost remove the autoplay attribute on the audio tag.

    then you can use javascript or jquery to control when the audio plays. In your case you wants the audio to play when all assets are loaded..so here is an example..

    //javascript
     window.onload = function() {
       document.getElementbyId("playAudio").play();
     }
     //jquery
     $(document).ready(function() {
       $("#my_audio").get(0).play();
     });
    

    if for any reason you still want some more delay let say 2seconds.. you can extend this further...

    var myAudio = document.getElementById("playAudio");
    //javascript
    window.onload = function() {
          setTimeout(function(){
           myAudio.play();
       }, 2000);
     }
    
     //jquery
    
     $(document).ready(function() {
         setTimeout(function(){
           $("#my_audio").get(0).play();
         }, 2000);    
     });
    

    PS. Use any of the two. I remember you said you're not familiar when JS. Best of luck pal