Issue
how can i play audio like its a notification.
as soon as the page is opened the notification audio starts beeping.
and it has to beep every 3 seconds
<!DOCTYPE html>
<html>
<head>
<script>
var aSound = document.createElement('audio');
aSound.setAttribute('src', '/path/beep.wav');
aSound.play();
</script>
</head>
<body>
<p>hello world</p>
</body>
</html>
Solution
The main problem of your code is, that the audio element is never added to the DOM. By calling document.createElement
you just create the element, but it is never added to your page.
To do so, you could use the following code line:
document.getElementsByTagName('body')[0].appendChild(aSound);
This will add the audio element to the end of the body
element. However, you can only do this after the DOM has been created. Currently, your code is executed before any element exists at all. The code must wait until after the page is fully loaded.
To play the sound repeatedly, you can simply use window.setInterval
if the audio file is less than three seconds long.
Below is a full example:
<!DOCTYPE html>
<html>
<head>
<script>
// Execute the code inside, after the page was loaded
window.addEventListener("load", () => {
var aSound = document.createElement('audio');
aSound.setAttribute('src', '/path/beep.wav');
// Append element to the DOM
document.getElementsByTagName('body')[0].appendChild(aSound);
aSound.play()
// Execute the code inside every 3 seconds
window.setInterval(() => {
aSound.play()
}, 3000);
})
</script>
</head>
<body>
<p>hello world</p>
</body>
</html>
Keep in mind, that many browsers these days block autoplaying audio and video content. I had to allow this in Firefox for my test page, so this is not suitable for public pages.
Answered By - JP_
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.