简体   繁体   English

从 JavaScript 调用时音频标签不起作用

[英]Audio tag not working when called from JavaScript

I am adding my HTML & js file which I am using.我正在添加我正在使用的 HTML & js 文件。 I think there is problem in sound.play(), other than it complete code is working fine.我认为 sound.play() 中存在问题,除了完整的代码工作正常。 I have checked it using console.我已经使用控制台检查过它。

HTML HTML

<body>
<audio id="sound">
</audio>
<button onclick="playSound()"><i class="fas fa-volume-up"></i></button>
</body>

JS JS

sound = document.getElementById("sound");
sound.setAttribute("src",https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3);
function playSound(){
    sound.play();
    console.log("hello");
}

...well, first off, maybe put quotes around your source URL, and when consider your HTML --> when you load your script in HTML header - browser will execute it after it's (the script) loaded, but the DOM content isn't loaded yet (simply, getElementById would return undefined..., so (check the Dom / dom events and such, and either wrap the scripts' with ie `window.addEventListener('DOMContentLoaded / load'... ): ...好吧,首先,也许在你的源 URL 周围加上引号,当考虑你的 HTML 时 --> 当你在 HTML 中加载你的script时 header - 浏览器将在它(脚本)加载后执行它,但 DOM 内容是尚未加载(简单地说, getElementById将返回未定义的...,因此(检查 Dom / dom 事件等,并使用 ie `window.addEventListener('DOMContentLoaded / load'... 包装脚本'):

<!doctype html>

<html>
  <head>
    <link rel="stylesheet" href="lib/style.css">
  </head>

  

I am adding my HTML & js file which i am using. I think their is problem in sound.play(), other than it complete code is working fine. I have checked it using console.

HTML

<body>
<audio id="sound">
</audio>
<button onclick="playSound()"><i class="fas fa-volume-up">Play</i></button>
    <script src="lib/script.js"></script>
</body>
</html>
const sound = document.getElementById("sound");
sound.setAttribute("src", "https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3");

function playSound() {
  sound.play();
  console.log("hello");
}

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

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