Html5如何只播放一首歌并重新播放

时间:2017-05-03 19:23:05

标签: javascript html5 audio

嗨,我已经跋涉多年,无法找到答案。我想要做的是在网站上拥有多个音频文件,并且只允许一次播放一首歌曲。但是如果你播放一首歌然后播放另一首歌然后回到第一首歌,我希望那首歌从头开始,而不是从我离开的地方开始。这是我到目前为止的代码



 document.addEventListener('play', function(e){
        var audios = document.getElementsByTagName('audio');
        for(var i = 0, len = audios.length; i < len;i++){
            if(audios[i] != e.target){
                this.currentTime = 0;
                audios[i].pause();
            }
        }
    }, true);
        

   
&#13;
    <div>
    <p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
        <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
            <I>Your browser does not support the audio element.</I>
        </audio>
        </div>
        <div>
            <p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
            <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
                <I>Your browser does not support the audio element.</I>
            </audio>
        </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

我认为你的eventListener已关闭,不确定循环。先试试这个:

var myAudio = document.querySelectorAll('audio');

for(var i=0; i<myAudio.length; i++) {
  	myAudio[i].addEventListener('play', function() {
		this.currentTime = 0;
		this.play();
	});
}
<div>
  <p class="song">
    <h3><strong>#1 Intro - The Oath</strong></h3>
    <p>
      <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<span>Your browser does not support the audio element.</span>
</audio>
</div>
<div>
  <p class="song">
    <h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3>
  </p>
  <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
  <span>Your browser does not support the audio element.</span>
  </audio>
</div>

在旁注中我不认为<I>是属性html标签。已更改为<span>

答案 1 :(得分:0)

您正在侦听(传播的)播放事件的文档,因此this.currentTime = 0;是文档。

audios[i].currentTime=0更改为<p class="price"> <span class="woocommerce-Price-amount amount"> <span class="woocommerce-Price-currencySymbol">R</span> 102.00 </span> </p>