16

I inserted the audio in html. But the audio gets started before the entire page loads. I want the audio to be played after the entire page gets loaded.

<audio src="bg.mp3" autoplay="autoplay" loop="loop"></audio>

Can anyone help me in this.

Priya Sunanthan
  • 441
  • 1
  • 8
  • 18

4 Answers4

30

You're going to need JavaScript for that. Remove the autoplay attribute:

<audio id="my_audio" src="bg.mp3" loop="loop"></audio>

and add a script like this:

window.onload = function() {
    document.getElementById("my_audio").play();
}

Or if you use jQuery:

$(document).ready(function() {
    $("#my_audio").get(0).play();
});
Aioros
  • 4,373
  • 1
  • 18
  • 21
10

Just Copy and Paste this Code in Body section of your HTML Code.

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

and make sure that your audio file should be in same folder.

pistou
  • 2,799
  • 5
  • 33
  • 60
Rajesh
  • 109
  • 1
  • 3
  • what if the audio file is elsewhere? How to do it then? – Shefali Sep 25 '17 at 13:24
  • 2
    I'm getting this error: `DOMException: play() failed because the user didn't interact with the document first.` – Knowledge Seeker Jul 02 '20 at 05:23
  • @KnowledgeSeeker You are getting this cause the browser is blocking the auto play. You can find more in https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide#Autoplay_and_autoplay_blocking – akatran Oct 07 '20 at 15:26
3

I think you must use JS (jQuery) function to do get document ready

$(document).ready(function()

Play an audio file using jQuery when a button is clicked

You have answer here (if I follow you right)

Community
  • 1
  • 1
0

For a repeated tone place the below code

        <audio src="./audio/preloader.mp3" autoplay="autoplay" loop="loop"></audio>

and for a single time, remove the loop. Then it should be like this

        <audio src="./audio/preloader.mp3" autoplay="autoplay"></audio>
Trinadh Koya
  • 1,089
  • 15
  • 19