jquery播放停止音频文件

时间:2018-02-12 12:14:08

标签: jquery audio toggle

我有一个歌曲列表,我用来访问它们的方式是:

<a href="path to song 1">play</a>
<a href="path to song 2">play</a>
...

当点击链接时,歌曲开始播放,并使用jquery这样做:

$('a').on('click', function() {
    var path = $(this).attr('href');
    var song = new Audio(path);
    song.play();
});

如何在点击链接时进行播放/停止切换?

1 个答案:

答案 0 :(得分:1)

切换play()pause()这样的函数:

var isPlaying = false
$("a").on("click", function(e) {
  e.preventDefault();

  var path = $(this).attr('href');
  var song = new Audio(path);

  if (!isPlaying) {
    isPlaying = true;
    song.play();
    $(this).text("Pause")
  } else {
    isPlaying = false;
    song.pause();
    $(this).text("Play");
  }

  console.log(isPlaying);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a href="path to song 1">play</a>
<a href="path to song 2">play</a>