[英]How to play many audio files with one html5 audio player
我们正在尝试制作一个html5音频播放器,其中我们有多个.mp3 file
,我们以表格形式显示使用loop with php
我们实际上想要:当我们点击每个mp3 file
然后它应该只播放一个界面就像http://gaana.com一样 。
我们做了什么 :
<?php
if(isset($_GET['song'])) {
$song_name = $_GET['song'];
echo "<audio id=\"audio1\" src=\"$song_name.mp3\" controls preload=\"none\" type=\"audio/mp3\" autobuffer autoplay></audio>";
}
?>
<script>
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function EvalSound1(soundobj1) {
var thissound=document.getElementById(soundobj1);
thissound.pause();
}
</script>
在上面的代码中,我们使用get
方法获取.mp3 file
,我们在url中传递mp3 file
名。
示范代码:
var tracks = ['https://archive.org/download/testmp3testfile/mpthreetest.mp3', 'http://www.tonycuffe.com/mp3/tail%20toddle.mp3']; Array.prototype.map.call(document.querySelectorAll("button"), function(element, index){ element.addEventListener("click", changeTrack.bind(null, tracks[index]), false); }); var autoPlay = true; function changeTrack(track) { var audioElement = document.getElementById("audio1"); audioElement.src = track; } audioElement.addEventListener("canplay", startPlaying, false); function startPlaying() { if (autoPlay) { this.play(); } }
<button>Track 1</button> <button>Track 2</button> <audio id="audio1" src="song_name.mp3" controls preload="none" type="audio/mp3" autobuffer autoplay></audio>";
核心代码(实际解决方案)
var autoPlay = true;
function changeTrack(track)
{
var audioElement = document.getElementById("audio1");
audioElement.src = track;
}
audioElement.addEventListener("canplay", startPlaying, false);
function startPlaying()
{
if (autoPlay)
{
this.play();
}
}
当有人点击另一个音频链接时,它应该调用函数changeTrack()
其中一个参数引用了track的url。 如果曲目已加载,它将开始播放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.