Update: In the recent updates of Chrome, you might face difficulties for autoplay as you will need to use
You may get error like this: Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.
Google chrome is very much strict to defense the noise autoplay on a webpage.
Play this video tutorial to learn more
Note that: For the recent updates of chrome and some other browsers you should try this:
Navigate to Google Chrome Settings, Search permissions and give audio permission,
You can also add your page link in allow section
(Mayuresh Deshmukh commented on this post)
So before showing you that directly I would like to show you how audio file is played in HTML.
<!DOCTYPE html> <html> <head> <title>My Audio</title> </head> <body> <audio src="mysong.mp3" id="my_audio" loop="loop" autoplay="autoplay"></audio> </body> </html>
So our full code will look like this
will run this function after page load.
Here document.getElementById() method is responsible for getting the audio file by its id.
Later, play() method is used to play the audio file.
Special Note: The audio tag is used in the body tag not in the head tag, because if you insert it into the head tag the browser will automatically load the media data in the body section. You can use your browser’s inspect option to see what happens if you put the audio tag in the head tag.
So it’s better to put the audio tag in the body tag.
Feel free to write in the comment section and watch the video embedded on this page to learn how to set the time delay to play your audio file on the webpage.