Javascript音频控件自动播放播放暂停

时间:2017-04-23 01:07:37

标签: javascript jquery audio

我的应用程序上有一个音频循环,我想让它在播放和暂停之间自动播放和切换图标。但不要在暂停和播放之间切换

JS

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'bglaughs.mp3');

audioElement.play();

audioElement.addEventListener('ended', function() {
  this.currentTime = 0;
  this.play();
}, true);

if(audioElement.paused && audioElement.currentTime > 0 && !audioElement.ended) {
  $(document).on('click', '.play', function() {
          audioElement.play();
      $(this).removeClass('play').addClass('pause');
      $('a .fa-volume-off').removeClass('fa-volume-off').addClass('fa-volume-up');
  });

} else {
  $(document).on('click', '.pause', function() {
          audioElement.pause();
      $(this).removeClass('pause').addClass('play');
      $('a .fa-volume-up').removeClass('fa-volume-up').addClass('fa-volume-off');
  });
}

HTML

<a href="#" id="music" style="color:black" class="play"><i class="fa fa-volume-up fa-2x" aria-hidden="true"></i></a>

更新

我设法获得了自动播放和切换工作但是最初需要2次点击才能停止音频然后在正常情况下切换恢复。关于它为什么这样做的任何帮助?

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'bglaughs.mp3');

audioElement.load();
audioElement.addEventListener("canplay", function() {
  audioElement.play();
}, true);

audioElement.addEventListener('ended', function() {
  this.currentTime = 0;
  this.play();
}, true);


  $(document).on('click', '.play', function() {
          audioElement.play();
      $(this).removeClass('play').addClass('pause');
      $('a .fa-volume-off').removeClass('fa-volume-off').addClass('fa-volume-up');
  });


  $(document).on('click', '.pause', function() {
          audioElement.pause();
      $(this).removeClass('pause').addClass('play');
      $('a .fa-volume-up').removeClass('fa-volume-up').addClass('fa-volume-off');
  });

2 个答案:

答案 0 :(得分:2)

由于音频正在播放加载...

只需设置锚点的onload类即可暂停 你的代码是正确的。

<a href="#" id="music" style="color:black" class="pause">

Working CodePen here

答案 1 :(得分:0)

IMO,你可以用更少的代码处理这个问题:

audioElement = new Audio('bglaughs.mp3');
audioElement.addEventListener("canplay", function() {
  audioElement.play();
}, false);
audioElement.addEventListener('ended', function () {
        this.currentTime = 0;
        this.play();
}, false);

$('#music').on('click', function(e) {
    e.preventDefault();
    var volIcon = $(this).find('i');
    volIcon.toggleClass('fa-volume-up fa-volume-off');
    if (volIcon.hasClass('fa-volume-off')) {
        audioElement.pause();
    } else {
        audioElement.play();
    }
});
相关问题