Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a sound on page load using JavaScript

How can I play a sound file when the onload event fires using JavaScript?

For example:

If I have a webpage, when a user clicks on a button and this will pop-up a window. While the pop-up window is loading, the page will play a sound file.

like image 345
Jin Yong Avatar asked Feb 19 '23 00:02

Jin Yong


1 Answers

Add a HTML5 audio element into your document:

 <audio id="foobar" src="yoursample.ogg" preload="auto"> 

Set it hidden via CSS:

 #foobar { display: none }

On the any JavaScript event handler play the audio:

var sample = document.getElementById("foobar");
sample.play();

For more information

https://developer.mozilla.org/en-US/docs/Using_HTML5_audio_and_video

Depending on your web application purpose you might want to support old browsers:

http://www.misfitgeek.com/play-sound-in-html5-and-cross-browser-support-with-backward-compatability/

like image 197
Mikko Ohtamaa Avatar answered Feb 27 '23 10:02

Mikko Ohtamaa