简体   繁体   English

页面加载后如何播放mp3?

[英]How to play mp3 after page load?

After creating my demo github pages.创建我的演示 github 页后。 I put following code into the index.html file:我将以下代码放入 index.html 文件中:

 <html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       <title>My TITLE</title>
       <link rel="icon" type="image/x-icon" href="images/icon.ico">
    </head>
    
    <body>
       
       <iframe src="2-seconds-silence.mp3" allow="autoplay" id="audio" style="display: none" hidden=""></iframe>
       <audio id="player" autoplay loop>
          <source src="hello.mp3" type="audio/mp3">
       </audio>
    </body>
 </html>

However after loading the page by chrome, it didn't run.但是,在通过 chrome 加载页面后,它没有运行。 Is there any way to fix this?有没有什么办法解决这一问题?

You can try it like that.你可以这样试试。 Attribute list: https://www.w3schools.com/jsref/dom_obj_audio.asp属性列表: https://www.w3schools.com/jsref/dom_obj_audio.asp

 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My TITLE</title> <link rel="icon" type="image/x-icon" href="images/icon.ico"> </head> <body> <iframe src="2-seconds-silence.mp3" allow="autoplay" id="audio" style="display: none" hidden=""></iframe> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { var audioTag = document.createElement("AUDIO"); audioTag.setAttribute("src","hello.mp3"); document.body.appendChild(audioTag); }, false); </script> </body> </html>

Check this:检查这个:

<audio src="mysong.mp3" id="my_audio" loop="loop"></audio>
<script type="text/javascript">
window.onload=function(){
  document.getElementById("my_audio").play();
}

First grab the audio element using Javascript. for eg: const audio = document.queryselector("#audioId") then apply funtion window.addEventListener("load",() => {audio.play()})首先使用 Javascript 获取音频元素。例如: const audio = document.queryselector("#audioId")然后应用函数window.addEventListener("load",() => {audio.play()})

correct autoplay attribute.正确的自动播放属性。 Instead of 'autoplay=" "' just leave 'autoplay', same for 'loop'.而不是 'autoplay=" "' 只保留 'autoplay','loop' 也是如此。

Cheers干杯

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

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