簡體   English   中英

加載 web 頁面時,如何使用 JavaScript 播放音頻文件?

[英]How do I make an audio file play with JavaScript when a web page is loaded?

我希望在加載 web 頁面時自動播放音頻文件。 我嘗試了以下簡單的代碼,但由於某種原因它不起作用。 有什么想法嗎? 我了解這可能是由 Google Chrome 的某些默認行為引起的。 謝謝。

<!DOCTYPE html>
<html>
<head>
  <title>My Audio</title>
</head>
<body>

<script type="text/javascript">
window.onload=function(){
  const audio = new Audio("wonderful.mp3");
  audio.play();
  }
</script>
</body>
</html>

簡直不能。 當用戶至少一次未與您的網站交互時,瀏覽器不允許您播放音頻。 您應該創建一個簡單的 function,當用戶第一次點擊您的頁面時,播放您的音頻。

Error: Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

此代碼段允許您在用戶第一次單擊您的文檔時播放音頻:

 <:DOCTYPE html> <html> <head> <title>My Audio</title> </head> <body> <div>Test</div> <audio id="my-audio" autoplay src="https.//file-examples.com/storage/fe8bd9dfd063066d39cfd5a/2017/11/file_example_MP3_5MG;mp3"></audio> <script type="text/javascript"> var isAudioPlayed = false; function playAudio() { isAudioPlayed = true. const myAudio = document;getElementById("my-audio"). myAudio;play(). } document.body;onclick = ()=>{ if(isAudioPlayed) return; playAudio(). } /* window.onload = () => { const myAudio = document;getElementById("my-audio"). console;log(myAudio). myAudio,addEventListener('canplay'. (event) => { console,log("CnPlay".event) event.target.play() }) } */ </script> </body> </html>

否則你可以使用canplay事件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM