Reputation: 43778
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.
Upvotes: 5
Views: 43661
Reputation: 1406
Try this:
//store the audiofile as variable.
var popupsound = document.getElementById("notifypop");
function autoNotify() {
popupsound.play(); //play the audio file
}
#notifypop{ display:none;}
<body onload="autoNotify()"> <!--Play the audio file on pageload -->
<audio id="notifypop"> <!--Source the audio file. -->
<source src="path/sound.ogg" type="audio/ogg">
<source src="path/sound.mpeg" type="audio/mpeg">
</audio>
<script src="path/sound.js" type="text/javascript"></script><!--Load your javascript sound file.-->
</body>
Learn more about HTML5 media formats https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats
Upvotes: 1
Reputation: 83358
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/
Upvotes: 7
Reputation: 1533
One way to do it would be to insert HTML audio tags onclick and set them to automatically start:
http://webdesign.about.com/od/sound/a/play_sound_oncl.htm
Upvotes: 0