最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

onload - Play a sound on page load using JavaScript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Sep 27, 2012 at 23:16 Jin YongJin Yong 43.8k72 gold badges144 silver badges193 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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/en-US/docs/Using_HTML5_audio_and_video

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

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

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/en-US/docs/Web/HTML/Supported_media_formats

One way to do it would be to insert HTML audio tags onclick and set them to automatically start:

http://webdesign.about./od/sound/a/play_sound_oncl.htm

发布评论

评论列表(0)

  1. 暂无评论