我正在建立一个网页来预览歌曲,让观众听到每首歌的片段。
我不想做的是通过创建许多音频元素的多次调用来重新发明轮子,你可以看到我如何使用" sample"作为第一个,但我不想一遍又一遍地重复代码。
以下是目前的工作方式:
<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>
&#13;
答案 0 :(得分:0)
将MP3文件的网址传递到<a>
代码中的playSegment()调用,如下所示:
<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();
}
答案 1 :(得分: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();
}