【问题标题】:Play sound when button clicked html按钮单击html时播放声音
【发布时间】:2022-01-26 16:34:16
【问题描述】:

我想当你点击一个按钮时它会发出声音,我试过这个:

<script type="text/javascript">
        var audio = new Audio('audio_file.mp3');
</script>
<button id="Draw/Chat" onclick="audio.play();" type="button" style="font-weight:bold; background: none rgb(0, 255, 0); border: none; color: rgb(255, 255, 255); box-shadow: none; height: 52px; width: 110px; left: 190px; top: 80px; border-radius: 5px; cursor: pointer; position: absolute;">Draw/Chat</button>

【问题讨论】:

  • 请在发布问题之前尝试使用搜索功能检查是否已被问过(并回答过):stackoverflow.com/…
  • ...还考虑到音频文件可能需要一些时间才能加载,因此建议在执行之前检查它是否准备好播放。
  • ...最后,您可能需要检查音频文件的路径是否正确。在您的示例中,“audio_file.mp3”应该位于您的 HTML 页面所在的同一文件夹中;是这样吗?
  • 这能回答你的问题吗? Javascript Audio Play on click

标签: javascript html audio


【解决方案1】:
<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>

  </body>
</html>

请试试这个代码

【讨论】:

  • 这不起作用:/
  • stackoverflow.com/questions/18826147/…我检查过,它工作正常,请再检查一次。
  • @KpStar 复制和粘贴已经存在的答案有什么意义,而不是添加任何新的/不同的东西,而不是简单地在评论中链接它?
【解决方案2】:

onclick 函数中不要使用分号:

<script type="text/javascript">
        var audio = new Audio('audio_file.mp3');
</script>
<button id="Draw/Chat" onclick="audio.play()" type="button" style="font-weight:bold; background: none rgb(0, 255, 0); border: none; color: rgb(255, 255, 255); box-shadow: none; height: 52px; width: 110px; left: 190px; top: 80px; border-radius: 5px; cursor: pointer; position: absolute;">Draw/Chat</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 2012-10-08
    • 2012-06-16
    • 2016-01-24
    相关资源
    最近更新 更多