- first we will create a html file and add audio by using audio tag…..
- In this we add our audio src by audio tag in html and set our preload to auto specifies if and how the author thinks that the audio file should be loaded when the page loads..
- And then its done in html and we need to add our java script file .In this we add external javascript file by script src tag in html and put our refrence of java scrpit in script tag.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Play Audio</title> </head> <body> <!-- this is my audio tag --> <audio id="myAudio" src="./walen - Gameboy (freetouse.com).mp3" preload="auto"></audio> <!-- and below i add my external java scriptfile --> <script src="script.js"></script> </body> </html>
2. now we will add some java script to play this audio ..
document.addEventListener('DOMContentLoaded', function() { const audioElement = document.getElementById('myAudio'); audioElement.muted = true; audioElement.play().then(() => { audioElement.muted = false; // Unmute after playback starts }).catch(error => { console.error('Audio playback was prevented by the browser:', error); }); });
” first we add event listner on whole document of our web page and DomcontentLoaded event and perform function in this function first we target our audio file by id ‘myAudio’ in this we firstly used muted event because browsers new policy is we can not play audio without user interaction or directly on reloading web pages so first we add muted our audio file.. and when it will play then our muted property will be false and our audio fill will be ring in our webpage background…”
Note : – “Make Sure To Confirm that Your browser Is not Under Autoplay Policy Restriction Otherwise It Will Not Play.”