网页播放器系列教程(四)–功能开发

(三)功能开发

接上文,我们现在开始编写Javascript代码,前文我们主文件已经引入了js文件,只需在js文件中编写代码。

1.播放音频;

怎样才能让页面播放音频呢?这需要“audio”标签,但是我们不是在页面总插入改标签,而是用JS实现,只需编写如下代码:

var Musicaudion = document.createElement("AUDIO")Musicaudion.setAttribute(‘autoplay‘,true)document.body.appendChild(Musicaudion);Musicaudion.setAttribute("src", "mp3/01.mp3");

这里面要在项目根目录中添加mp3目录,并添加01.mp3音频文件,这样我们的网页就可以播放 "mp3/01.mp3"了。

但是这样写十分不利于我们复用,同时我们需要播放歌曲列表,所以进行了简单改进。

一定义播放歌曲列表内容:

var songlist = [{ "songname": "我的老朋友", "songurl": "01.mp3", "songer": "张三" }, { "songname": "Angelina", "songurl": "02.mp3", "songer": "李四" }, { "songname": "New Thang", "songurl": "03.mp3", "songer": "王五" }, { "songname": "Boys", "songurl": "04.mp3", "songer": "boy" }, { "songname": "在一起", "songurl": "05.mp3", "songer": "girl" }, { "songname": "我的老朋友", "songurl": "01.mp3", "songer": "张三" }, { "songname": "Angelina", "songurl": "02.mp3", "songer": "李四" }, { "songname": "New Thang", "songurl": "03.mp3", "songer": "王五" }, { "songname": "Boys", "songurl": "04.mp3", "songer": "boy" }, { "songname": "我的老朋友", "songurl": "01.mp3", "songer": "张三" }, { "songname": "Angelina", "songurl": "02.mp3", "songer": "李四" }, { "songname": "New Thang", "songurl": "03.mp3", "songer": "王五" }, { "songname": "Boys", "songurl": "04.mp3", "songer": "boy" }]

二是定义播放函数以便播放歌曲时重复利用。

上面定义的“Musicaudion”和“两个全局变量”,同时我们还需要定义一个全局变量currentid,表示前歌曲播放序号代码如下: 

//当前歌曲播放序号,最小值为0,最大值为songlist数组的长度减一var currentid=0;

 在函数中我们需要用到,具体代码如下: 

//播放歌曲函数,songid表示songlist数据数组序号function PlaySong(songid) {// 设置播放文件路径,从数组songlist中获取Musicaudion.setAttribute("src", "mp3/" + songlist[songid].songurl);//获取歌曲名称Song_Name和歌曲作者Singer并动态设置document.getElementById("Song_Name").innerHTML = songlist[songid].songname;document.getElementById("Singer").innerHTML = songlist[songid].songer;//播放歌曲Musicaudion.play();}

 

这样我们的播放函数就编写好了,最开始的代码“Musicaudion.setAttribute("src", "mp3/01.mp3");”修改为“PlaySong(currentid);”

2.歌曲播放、暂停、切换功能;

实现这些功能我们首先获取HTML中div变成JS对象在进行相应设置,具体代码如下,有详细的注解:

播放暂停功能代码 

//定义全局变量isPlay,0表示当前歌曲状态播放状态,1表示暂停状态var isPlay = 0;//首先获取ID为“Button_play”按钮,然后设置单击事件document.getElementById("Button_play").onclick = function() {//当歌曲为播放状态,单击变为暂停状态,歌曲暂停if (isPlay == 0) {//设置我们定义的暂停样式this.className = "Button_pause";isPlay = 1;Musicaudion.pause();} else {//当歌曲为暂停状态,单击变为播放状态,歌曲播放this.className = "Button_play";isPlay = 0;Musicaudion.play();}};

 上一首,下一首歌曲功能。 

//上一首document.getElementById("Button_Pre").onclick = function() {//判读是否为第一首歌曲,如果是第一首歌曲,序号变为最后一首歌曲,不是第一首歌曲,歌曲切换到下一首if (currentid > 0) {currentid--;} else {
currentid
= songlist.length - 1;}PlaySong(currentid)}//下一首document.getElementById("Button_next").onclick = function() {if (currentid < songlist.length - 1) {currentid++;} else {currentid = 0;}PlaySong(currentid)}

 

3.播放进度条功能;

该功能我们需要一个定时函数,随着歌曲的播放进度实时进行更新进度条,同时为进度条添加单击功能,调整播放进度,局具体代码如下: 

//设置定时器var t = setInterval(function() {//获取歌曲当前播放百分比var percent = Math.floor(Musicaudion.currentTime / Musicaudion.duration * 10000) / 100 + "%";//设置播放头位置document.getElementById("Progressbar_playHead").setAttribute("style", "left:" + percent);//设置歌曲当前时间document.getElementById("Songcurrenttime").innerHTML = conversion(Musicaudion.currentTime)}, 100)//单击进度条 调整发播放进度
document.getElementById("Progressbar_Box").onclick = function(e) {//获取鼠标单击进度条位置var x = (e || window.event).clientX;//计算进度条移动距离var left = x - this.offsetLeft - document.getElementById("Progressbar_playHead").offsetWidth;//设置播放头位置document.getElementById("Progressbar_playHead").style.left = left + ‘px‘;//计算总的进度条长度var maxwidth = document.getElementById("Progressbar_Box").offsetWidth - document.getElementById("Progressbar_playHead").offsetWidth;//计算当前点击进度百分比百分比var p = left / maxwidth//设置当前播放时间点到点击位置Musicaudion.currentTime = p * Musicaudion.duration;//播放音乐Musicaudion.play();};

 时间格式显示函数。 

//时间格式转换函数function conversion(value) {let minute = Math.floor(value / 60)minute = minute.toString().length === 1 ? (‘0‘ + minute) : minutelet second = Math.round(value % 60)second = second.toString().length === 1 ? (‘0‘ + second) : secondreturn `${minute}:${second}`}

 这样我们的进度条已经设置完成了,这里介绍一下setInterval函数,这个函数是一个实现定时调用的函数,可按照指定的周期(以毫秒计)来调用函数或计算表达式。setInterval方法会不停地调用函数,直到 clearInterval被调用或窗口被关闭。

4.随机播放,循环播放功能。

这部分的代码也是很简单,大同小异,代码如下,注释很详细: 

var isPlayState=0;//0顺序播放,1随机播放,2单曲循环//随机播放按钮var randomBtn = document.getElementById("SongOption_Shuffle");var onereplayBtn = document.getElementById("SongOption_Replay");randomBtn.onclick = function() {if (isPlayState == 1) {isPlayState = 0;this.className = "SongOption_Shuffle"return;}if (isPlayState == 2) {onereplayBtn.className = "SongOption_Replay";}isPlayState = 1;this.className = "SongOption_Shuffle_on"}onereplayBtn.onclick = function() {if (isPlayState == 2) {isPlayState = 0;this.className = "SongOption_Replay"return;}if (isPlayState == 1) {randomBtn.className = "SongOption_Shuffle";}isPlayState = 2;this.className = "SongOption_Replay_on"}

 这里需要更改一下CSS代码,“#SongOption_Shuffle”,更改为“.SongOption_Shuffle”;“#SongOption_Shuffle_on”,更改为“.SongOption_Shuffle_on”;“#SongOption_Replay”,更改为“.SongOption_Replay”;“#SongOption_Replay_on”,更改为“.SongOption_Replay”。Html代码中id为“SongOption_Shuffle”添加css样式“SongOption_Shuffle”;id为“SongOption_Replay”添加css样式“SongOption_Replay”。原因是我们JS代码中要切换样式。

这样我们的样式功能切换就实现了,还需要在setInterval函数中添加代码实现循环、重复功能,具体代码如下: 

//判断个歌曲是否结束if (Musicaudion.ended) {if (isPlayState == 0) //顺序播放{if (currentid < songlist.length - 1) {currentid++;} else {currentid = 0;}} else if (isPlayState == 1) //随机播放{currentid = Math.floor(Math.random() * songlist.length - 1)} else //单曲循环{currentid = currentid;}PlaySong(currentid);}

 

5.音量调节功能;

音量调节需要一个初始数值,所以我们进行了如下设置: 

//初始音量var SoundStart = 0.3;//计算音量最大移动数值var Soundmax = document.getElementById("SongOption_SoundBox").offsetWidth - document.getElementById("SongOption_SoundHead").offsetWidth;//设置音量初始位置document.getElementById("SongOption_SoundHead").style.left = (Soundmax * SoundStart) + ‘px‘;document.getElementById("SongOption_SoundCurrent").style.width = SoundStart * 100 + ‘%‘;Musicaudion.volume = SoundStart;//音频载入完成Musicaudion.onloadedmetadata = function() {//歌曲总的显示时间document.getElementById("Songalltime").innerHTML = conversion(Musicaudion.duration)}

 设置音量调节功能,具体代码如下: 

//调整音量document.getElementById("SongOption_SoundHead").onmousedown = function(e) {var x = (e || window.event).clientX;var l = this.offsetLeft;var max = document.getElementById("SongOption_SoundBox").offsetWidth - this.offsetWidth;document.onmousemove = function(e) {var thisX = (e || window.event).clientX;var to = Math.min(max, Math.max(-2, l + (thisX - x)));if (to < 0) {to = 0;}document.getElementById("SongOption_SoundHead").style.left = to + ‘px‘;//此句代码可以除去选中效果window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();Musicaudion.volume = to / max;//document.querySelector(‘.now‘)document.getElementById("SongOption_SoundCurrent").style.width = to / max * 100 + ‘%‘;}//注意此处是document 才能有好的拖动效果document.onmouseup = function() {document.onmousemove = null;};}

 

6.音频列表。

初始数据 

var htmlinsert = "";for (var i = 0; i < songlist.length; i++) {htmlinsert += ‘<li onclick="PlaySong(‘ + i + ‘)"><span>‘ + songlist[i].songname + ‘</span> </li>‘;}var musiclistbox = document.getElementById(‘Songlist_box‘);musiclistbox.innerHTML = htmlinsert;var lis = musiclistbox.childNodes;var onesong = lis.item(0);var gundongheight = onesong.offsetHeight;

 在play函数中添加如下代码 

//设置歌曲库for (var i = 0; i < lis.length; i++) {if (songid == i) {lis.item(i).setAttribute("class", "currentSong")} else {lis.item(i).setAttribute("class", "")}}//歌曲库滚动到相应歌曲if (songid > 2) {document.getElementById(‘playMusic_Songlist‘).scrollTop = gundongheight * (songid - 1);} else {document.getElementById(‘playMusic_Songlist‘).scrollTop = 0;}

这样我们的所有js代码已经输入完成,播放器的功能全部实现,下一步我们将对代码精简提炼,进行封装。

需要源代码的可以留言。

 

相关文章