我想在我的页面加载后播放声音。以下是我的javascript代码:
var playAudio = $("#sound")[0];
playAudio.play();
和html代码:
<audio id="sound">
<source src="../music/hide.ogg" type="audio/ogg">
<source src="../music/hide.mp3" type="audio/mp3">
</audio>
console:Uncaught(promise中)DomeException:play()失败,因为用户没有首先与文档交互。
大多数浏览器都会阻止网页播放的与用户交互无关的音频(请参阅https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide).对于用户交互,我指的是按下按钮之类的事情。你不能做任何反对的事。
但是您可以添加一个开始按钮,显示页面并启动音乐,如下所示:
const startbtn = document.getElementById("startbtn");
const content = document.getElementById("content");
const loader = document.getElementById("loader");
const music = document.getElementById("music");
//Add an event listner to the start button
startbtn.addEventListener("click", () => {
//Show the loader and hide the button
loader.style.display = "";
startbtn.style.display = "none";
//Wait for the music to start
music.play().then(() => {
//Hide the loader and show the content
content.style.display = "";
loader.style.display = "none";
});
});
<!-- The start button --->
<button id="startbtn">Start</button>
<!-- The actual content, hidden by default -->
<div id="content" style="display: none;">
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
<p>Bla</p>
</div>
<!-- This is displayed when the user has pressed the start button, but the music is still loading -->
<div id="loader" style="display: none;">
<p>Loading ...</p>
</div>
<!-- The music. It is started by the Javascript -->
<audio id="music" src="https://opengameart.org/sites/default/files/audio_preview/swing_0.mp3.ogg" style="display: none;" loop></audio>