单击并停止播放音频

时间:2018-11-22 08:20:41

标签: javascript audio

<button class="button" style="width: 200px;" onclick="playSound()">Play sound</button>

function playSound() {
          audio.pause();
          var audio = new Audio('V2018-Museum-filer/mp3file.mp3');
          audio.play();
        }

当单击多个tiems按钮以多次启动音频时,我想停止已经播放的音频以重新播放。我怎样才能做到这一点?我收到一条错误消息,说音频未定义。

1 个答案:

答案 0 :(得分:0)

希望这对您有帮助...

单击该按钮时,音频将暂停并在第二次单击时重新开始。

function playSound() {
  var audioControl = document.getElementById('sound');
  var btn = $("#player");

  if (btn.click && audioControl.paused !== true) {
    audioControl.pause();
  } else if (btn.click && audioControl.paused === true) {
  audioControl.currentTime = 0;
    audioControl.play();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="sound" controls>
  <source src="http://www.largesound.com/ashborytour/sound/brobob.mp3" type="audio/mpeg">
</audio>
<button id="player" style="width: 200px;" onclick="playSound()">Play sound</button>