使用 JavaScript 在页面加载时播放声音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12631420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:42:49  来源:igfitidea点击:

Play a sound on page load using JavaScript

javascriptonload

提问by Jin Yong

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

当使用 JavaScript 触发 onload 事件时,如何播放声音文件?

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.

如果我有一个网页,当用户点击一个按钮时,这将弹出一个窗口。在加载弹出窗口时,页面将播放声音文件。

回答by Mikko Ohtamaa

Add a HTML5 audio element into your document:

将 HTML5 音频元素添加到您的文档中:

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

Set it hidden via CSS:

通过 CSS 将其设置为隐藏:

 #foobar { display: none }

On the any JavaScript event handler play the audio:

在任何 JavaScript 事件处理程序上播放音频:

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

For more information

想要查询更多的信息

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

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:

根据您的 Web 应用程序用途,您可能希望支持旧浏览器:

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

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

回答by devsam247

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

了解有关 HTML5 媒体格式的更多信息 https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats

回答by Alex Kalicki

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

一种方法是插入 HTML 音频标签 onclick 并将它们设置为自动启动:

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

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