本文在最基礎的播放器寫法上補上了 playlist 能力,透過 MakeList() 就能註冊多首歌曲,並支援上一首/下一首、播放暫停切換與循環播放。程式碼都在註解裡,有需求可以直接取用。
<!DOCTYPE html>
<html>
<head>
<title>Untitled Page</title>
</head>
<body style="font-family:Verdana; font-size:12px">
<script>
/*************************************************************
LovelyLife Player V1.0
*************************************************************/
var playid = "LovelyLifePlayer"
var status = "status"
var curId, arrPL, selected
var isStop, isLoop
arrPL = new Array()
cur = 0
curId = 0
isStop = false
selected = 0
isLoop = true
function songObj(Id, url, name) {
this.Id = Id
this.url = url
this.name = name
}
// 播放 / 暫停切換
function playAndpauseIt() {
if (document.getElementById(status).innerText == '暫停') {
document.getElementById(playid).controls.pause()
document.getElementById(status).innerHTML = '播放'
} else {
document.getElementById(status).innerText = '暫停'
document.getElementById(playid).controls.play()
}
}
function stopIt() {
isStop = true
document.getElementById(status).innerHTML = '播放'
document.getElementById(playid).controls.stop()
}
// 定時更新進度與自動下一首
function showTimer() {
var player = document.getElementById(playid)
var cps = player.controls.currentPositionString
var durs = player.currentMedia.durationString
var s = player.playState
if (s == 2 || s == 3)
document.getElementById('pos').innerText = " " + cps + "/" + durs + " "
else
document.getElementById('pos').innerText = " 00:00/" + durs + " "
if (s == 1) { // 播放結束
if (isLoop && (curId > (arrPL.length - 1))) {
curId = 0
return 0
}
clearIt()
if (curId < 0 || curId > arrPL.length) {
alert("當前沒有歌曲!,請查看播放列表!")
return false
}
nxtPlay()
}
if (s == 10 && arrPL.length > 0) nxtPlay()
}
function nxtPlay() {
isStop = true
if (curId > arrPL.length - 1) {
document.getElementById("songName").innerText = "沒有歌曲了,請選擇上一曲!"
document.getElementById(playid).URL = "NULL"
return false
}
curId++
clearIt()
setIt(curId)
PlayIt(curId)
}
function prePlay() {
isStop = true
if (curId < 0) {
document.getElementById("songName").innerText = "沒有歌曲了,請選擇下一曲!"
document.getElementById(playid).URL = "NULL"
return false
}
curId--
clearIt()
setIt(curId)
PlayIt(curId)
}
function PlayIt(cid) {
if (curId < 0 || curId > arrPL.length - 1) {
document.getElementById("songName").innerText = "當前沒有歌曲!,請查看播放列表!"
return false
}
var url = arrPL[cid].url
curId = cid
if (url == "None") {
document.getElementById("songName").innerText = "加載歌曲未找到!播放下一曲!"
nxtPlay()
return false
}
document.getElementById(playid).URL = url
document.getElementById("songName").innerText = arrPL[cid].name
}
function clearIt() {
if ((arrPL.length - 1 < 0) || selected < 0 || selected > arrPL.length) return false
}
function setIt(tid) {
if (tid < 0 || tid > arrPL.length - 1) {
document.getElementById("songName").innerText = "當前沒有歌曲!,請查看播放列表!"
return false
}
}
// 動態產生播放器與控制列
function InitPlay(songName, url, auto) {
var strTemp = '<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
strTemp += ' type="application/x-oleobject" width="0" height="0" id="' + playid + '"'
strTemp += ' style="position:relative; left:0px; top:0px; width:0px; height:0px;">\n'
strTemp += ' <param name="autoStart" value="' + auto + '">\n'
strTemp += ' <param name="balance" value="0">\n'
strTemp += ' <param name="currentPosition" value="0">\n'
strTemp += ' <param name="enableContextMenu" value="0">\n'
strTemp += ' <param name="enableErrorDialogs" value="0">\n'
strTemp += ' <param name="playCount" value="1">\n'
strTemp += ' <param name="rate" value="1">\n'
strTemp += ' <param name="uiMode" value="none">\n'
strTemp += ' <param name="volume" value="100">\n'
strTemp += ' <param name="URL" value="' + url + '">\n'
strTemp += '</object>\n'
strTemp += '<b>點播的歌曲: <font color=red id=songName>' + songName + '</font>'
strTemp += ' [<font id=pos></font>]'
strTemp += ' [<font onclick=playAndpauseIt() style="cursor:hand" id=' + status + '>播放</font>]'
strTemp += ' [<font onclick=stopIt() style="cursor:hand">停止</font>]'
if ((arrPL.length - 2) >= 0) {
strTemp += ' [<font onclick=prePlay() style="cursor:hand">上曲</font>]'
strTemp += ' [<font onclick=nxtPlay() style="cursor:hand">下曲</font>]'
}
strTemp += ' </b>'
document.getElementById('player').innerHTML = strTemp
setInterval('showTimer()', 1000)
}
// 點擊列表中的某一首直接播放
function playX(cur) {
PlayIt(cur)
clearIt()
setIt(cur)
curId = cur
selected = cur
}
// 註冊一首歌到播放列表
// 參數:ID、音樂 URL、歌曲名稱
function MakeList(Id, Url, Name) {
arrPL[cur] = new songObj(Id, Url, Name)
cur++
}
// 循環播放開關
function loopIt() {
if (isLoop) {
document.getElementById('sloop').innerText = "不循環"
isLoop = false
} else {
document.getElementById('sloop').innerText = "循環播放"
isLoop = true
}
}
</script>
<div id="player" style="width:70%"></div>
<script>
InitPlay("示例歌曲", "https://example.com/your.mp3", 1);
playAndpauseIt();
MakeList(1, "https://example.com/song1.mp3", "歌曲一");
MakeList(2, "https://example.com/song2.wma", "歌曲二");
MakeList(3, "https://example.com/song3.rm", "歌曲三");
</script>
</body>
</html>
這份程式碼示範的是完整的播放器邏輯骨架:以陣列 arrPL 存放歌單,curId 記住目前播放位置,showTimer() 每秒輪詢一次播放狀態,藉此更新進度條並在歌曲結束時自動跳下一首;isLoop 控制是否回到歌單頭部重新播放。
但必須老實說:這裡使用的 <object classid="CLSID:6BF52A52-..."> 是 Windows Media Player 的 ActiveX 控制項,只有在舊版 Internet Explorer 加 Windows 環境下才會動,在當今的 Chrome、Firefox、Safari、Edge 上完全無效。同時 innerText、window.attachEvent 也都是老 IE 專屬寫法。
因此這段程式今日的價值在於「播放列表的資料結構與狀態管理思路」,而不是能不能直接跑。要在現代瀏覽器上實作同樣的功能,把播放器換成 HTML5 的 <audio> 即可,其餘邏輯幾乎可以原封不動沿用:
var audio = new Audio();
var playlist = [{ name: '歌曲一', url: 'song1.mp3' }, { name: '歌曲二', url: 'song2.mp3' }];
var curId = 0;
function play(index) {
curId = index;
audio.src = playlist[index].url;
audio.play();
document.getElementById('songName').textContent = playlist[index].name;
}
audio.addEventListener('ended', function () {
play((curId + 1) % playlist.length); // 循環播放
});
這樣寫不但跨瀏覽器,還能直接用 audio.currentTime 與 timeupdate 事件取代每秒輪詢的 setInterval,效能與準確度都更好。
以上就是本文的全部內容,歡迎大家閱讀和參考。