jQuery:多个音频播放器按钮

时间:2016-06-15 12:50:45

标签: javascript jquery html5-audio

我想制作播放mp3音频的4个播放按钮。播放功能每4个按钮工作一次,但不幸的是暂停不适用于其中任何一个。也许暂停条件错了?

bundle exec rspec --tag ~http_request
<div class="audio-button">
    <audio src="media/test.mp3"></audio>
</div>
<div class="audio-button">
    <audio src="media/test2.mp3"></audio>
</div>
<div class="audio-button">
    <audio src="media/test3.mp3"></audio>
</div>
<div class="audio-button">
    <audio src="media/test4.mp3"></audio>
</div>

2 个答案:

答案 0 :(得分:1)

您需要在孩提时直接从按钮中获取音频元素并与之交互。您不需要使用构造函数克隆Audio对象。

$(document).ready(function() {
  var playing = false;

  // Add file names.
  $('.audio-button').each(function() {
    var $button = $(this);    
    var $audio = $button.find('audio');
    
    $($('<span>').text($audio.attr('src'))).insertBefore($audio);
  });

  // Add click listener.
  $('.audio-button').click(function() {
    var $button = $(this);    
    var audio = $button.find('audio')[0]; // <-- Interact with this!
    
    // Toggle play/pause
    if (playing !== true) {
      audio.play();
    } else {
      audio.pause();
    }

    // Flip state
    $button.toggleClass('playing');
    playing = !playing
  });
});
.fa.audio-button {
  position:      relative;
  display:       block;
  width:         12em;
  height:        2.25em;
  margin-bottom: 0.125em;
  text-align:    left;
}

.fa.audio-button:after {
  position:      absolute;
  right:         0.8em;
  content:       "\f04b";
}

.fa.audio-button.playing:after {
  content:       "\f04c";
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="fa audio-button">
  <audio src="media/test.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test2.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test3.mp3"></audio>
</button>
<button class="fa audio-button">
  <audio src="media/test4.mp3"></audio>
</button>

答案 1 :(得分:0)

你想在点击一个时停止其他三个吗?

如果是这样,你可以尝试:

$(document).ready(function () { $('.audio-button').click(function (e) { var button = $(e.target).closest('.audio-button'); var audio = button.find('audio'); var audioDom = audio.get(0); $('audio[data-is-playing]').not(audio).each(function (i, currentAudioDom) { var currentButton = $(currentAudioDom).closest('.audio-button'); currentButton.removeClass('playing'); currentButton.removeAttr('data-is-playing'); currentAudioDom.$audio.pause(); }); button.addClass('playing'); audio.attr('data-is-playing', ''); audioDom.$audio = audioDom.$audio || new Audio(audio.attr('src')); audioDom.$audio.play(); }); });

修正:

实际上我不确定音频元素本身是否是音频对象,如果是这样,你可以直接在audioDom / currentAudioDom元素上调用播放/暂停,而忘记$ audio的事情... < / p>