saifaldeen
saifaldeen

Reputation: 173

How could i delay an auto play audio /html5 by jquery

I have an autoplay audio in my page , its html5 audio when i open the webpage the audio directly plays , I want the audio be delayed three seconds then it plays ..

This is the code

<div class="audio">
            
                <audio autoplay> <source src="loading/harely.mp3" type="audio/mp3">  </audio>
            
            </div>

I tried this way by jquery , but the audio didn't delay

    $('.audio').delay(3000).append('<audio autoplay> <source src="loading/harely.mp3" type="audio/mp3">  </audio>');
<div class="audio">


</div>

Thank you

Upvotes: 1

Views: 2708

Answers (3)

enhzflep
enhzflep

Reputation: 13089

Rather than making life hard for anyone that attempts attempts maintenance of the page, why not simply put an audio element into the html (without the autoplay attribute set) and then use javascript to start it playing?

Something like the following will do it. (it doesn't work here in the page, since the src is invalid)

function byId(id){return document.getElementById(id)}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
  setTimeout( function(){ byId('myAudioElem').play() }, 3000 );
}
<audio id='myAudioElem' src='yourAudioFilenameHere.extension'></audio>

This presents a number of advantages over other suggestions thus far:

  1. There is an element clearly defined in the HTML - this:

    • makes maintenance easier
    • allows users that object to find and remove it from the DOM
  2. The browser begins to download and decode the audio immediately at the time the page is loaded. This helps ensure that it actually does begin playing after 3 seconds, rather than happening at some time after this - a time that will depend on the connection speed and the cpu speed of the viewing device.

You can easily hear the difference if you instead use a function for setTimeout like the following, making sure to specify the same audio-file as is done in the DOM - you'll get a noticeable echo when playing from localhost and an even larger (longer) echo when loading an element from another server.

 setTimeout( 
                function()
                { 
                    var audio = document.createElement('audio'); 
                    audio.src = 'yourAudioFilenameHere.extension';
                    audio.play();

                    byId('myAudioElem').play() 
                }, 
                3000 
            );

Upvotes: 1

Mohammad Kermani
Mohammad Kermani

Reputation: 5396

I believe it is much better to not mess with HTML elements, and using function JavaScript instead.

let playNow = function() {
 let audio = new Audio('YourMusic.mp3');
audio.play();
}

setTimeout(function(){ 
    playNow();
}, 5000);

See Demo

Upvotes: 1

Jaber
Jaber

Reputation: 277

Use a simple delay function

setTimeout(function(){ 
    // code here
}, 3000);

Upvotes: 1

Related Questions