2017-02-15 101 views
1

我正在建立一個網頁預覽歌曲,讓觀衆公開聆聽每首歌曲的片段。播放許多音頻文件關閉相同的音頻元素

我不想做的是通過創建許多調用許多音頻元素重新發明輪子,你可以看到我如何使用「樣本」作爲第一,但我不想一直重複代碼。

下面是它目前是如何工作的:

<html> 
 
    <head> 
 
     <style> 
 
      div{ 
 
       display: none; 
 
      } 
 
     </style> 
 
    </head> 
 
    <body> 
 
     <div> 
 
      <audio id="sample" src="BACKING unforgettable fire.mp3" controls preload> 
 
       <p>Your browser does not support the audio element</p> 
 
      </audio> 
 
     </div> 
 
     <br> 
 
     <a href="javascript:playSegment(10, 35);">BACKING unforgettable fire - <img src="http://www.auctioneerslive.co.uk/music/play.png"></a> 
 
     <script> 
 
      var audio = document.getElementById('sample'); 
 
      var segmentEnd; 
 
      audio.addEventListener('timeupdate', function(){ 
 
       if (segmentEnd && audio.currentTime >= segmentEnd){ 
 
        audio.pause(); 
 
       } 
 
       console.log(audio.currentTime); 
 
      }, false); 
 
      function playSegment(startTime, endTime){ 
 
       segmentEnd = endTime; 
 
       audio.currentTime = startTime; 
 
       audio.play(); 
 
      } 
 
     </script> 
 
    </body> 
 
</html>

回答

0

傳遞MP3文件的URL到playSegment()調用你的<a>標籤,就像這樣:

<a href="javascript:playSegment('BACKING unforgettable fire.mp3', 10, 35);">BACKING unforgettable fire - <img src="play.png"></a> 

然後修改您的playSegment()函數,如下所示:

function playSegment(fileURL, startTime, endTime){ 
    audio.src = fileURL; 
    audio.oncanplay = function(){ 
      segmentEnd = endTime; 
      audio.currentTime = startTime;  
      audio.play(); 
    }; 
    audio.load(); 
} 
+0

感謝您的信息,它似乎並沒有玩到現在進行這些更改 – smashit

+0

我已經更新了我的答案與校正,請覈對與嘗試該代碼。 – ablopez

+0

它仍然與getElementByID('sample')鏈接 - 如果我拿出它不起作用 – smashit

0

查看調整,但排序,感謝ablopez

function playSegment2(fileURL, startTime, endTime) 
{ 
    var audio = document.getElementById('sample'); 
    var segmentEnd; 

    audio.src = fileURL; 
    audio.oncanplay = function() 
    { 
     audio.addEventListener('timeupdate', function() 
     { 
      if (segmentEnd && audio.currentTime >= segmentEnd) 
      { 
       audio.pause(); 
      } 
      console.log(audio.currentTime); 

     }, false); 
     segmentEnd = endTime; 
     audio.currentTime = startTime;  
     audio.play();   
    }; 
    audio.load(); 
}