如何通过单击按钮切换音频播放()暂停()?

How to toggle audio play() pause() with a button click?

我在我的网站上添加了一个音频,打开网站时会播放该音频。现在我想添加 play/pause 按钮来切换音频。

我是这样尝试的:

<audio id="myAudio" autoplay >
 <source src="mp3/background-music.mp4" type='audio/mp4'>
 Your user agent does not support the HTML5 Audio element.
</audio>

<a type="button" class="play-pause" title="play/pause"><i class="fa fa-pause"></i></a>


<script type="text/javascript">
  $(document).ready(function() {
    var playing = false;

    $('a.audio-btn').click(function() {
        if (playing == false) {
            document.getElementById('myAudio').play();
            playing = true;
            $(this).text("stop sound");

        } else {
            document.getElementById('myAudio').pause();
            playing = false;
            $(this).text("restart sound");
        }
    });
  });
</script>  

但它对我不起作用。谁能告诉我哪里出错了?

到底是什么不起作用?按钮没有出现,是不是不起作用?

我建议使用如下内容:

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
};
myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};

将您的 $('a.audio-btn') 更改为 $('a.play-pause')

出于演示目的,我添加了 video 标签,要使用音频,您可以将 video 替换为 audio 标签并使用

$('.play-pause')

而不是

$('a.audio-btn')

对于音频,请在 video 标签处使用它:

<audio id="myAudio" autoplay>
 <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='audio/mp4'>
   Your user agent does not support the HTML5 Audio element.
</audio>

$(document).ready(function () {
 var playing = true;
 $('.play-pause').click(function () {
  if (playing == false) {
   document.getElementById('myAudio').play();
   playing = true;
   $(this).text("Sop Sound");

  } else {
   document.getElementById('myAudio').pause();
   playing = false;
   $(this).text("Restart Sound");
  }
 });
});
a {
  background: #000;
  color: #fff;
  cursor: pointer;
  padding: 10px;
}
video {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myAudio" autoplay>
 <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='video/mp4'>
 Your user agent does not support the HTML5 Audio element.
</video>
<a type="button" class="play-pause" title="play/pause">Play / Pause</a>