简体   繁体   English

在 JavaScript 或 jquery 的后台页面加载时自动播放音乐

[英]Play the music automatically on page load in the background in JavaScript or jquery

I'm trying to play the music or mp3 audio once the page load I tried to load the function once the page load but it is not working only once I click on the button the music will start playing below the code我正在尝试在页面加载后播放音乐或 mp3 音频我在页面加载后尝试加载 function 但只有在我单击按钮后它才不起作用音乐将在代码下方开始播放

HTML HTML

<audio id="audio1" src="bk.mp3" >
<p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>
<button onclick="playAudio()" type="button" id="pp">Play Audio</button>
<button onclick="pauseAudio()" type="button" id="pp2">Pause Audio</button>

Javascript Javascript

<script>
var x = document.getElementById("audio1"); 

function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 

</script>

the above code will play the audio once click on the button play but my point I need it to start playing automatically on load the same for Jquery i tried different method but the same only working on click上面的代码将在单击按钮播放后播放音频,但我的观点是我需要它在加载时自动开始播放 Jquery 我尝试了不同的方法,但仅在单击时相同

Simple implementation简单的实现

First, add an audio element to the page and load the audio's source with the src attribute:首先,在页面中添加一个音频元素并使用 src 属性加载音频的源:

<audio src="https://www.bensound.com/bensound-music/bensound-moose.mp3"></audio>

Next, use JavaScript to listen to the DOMContentLoaded event, select the audio event and call audio.play():接下来,使用 JavaScript 监听 DOMContentLoaded 事件,select 音频事件并调用audio.play():

window.addEventListener("DOMContentLoaded", event => {
  const audio = document.querySelector("audio");
  audio.volume = 0.2;
  audio.play();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM