實例:一個簡單的播放器效果。
實現(xiàn)的功能:
1點擊播放按鈕。音頻開始播放。
2播放的同時,進(jìn)度條在不停的更新走動
3點擊暫停按鈕,音頻停止播放
4當(dāng)音頻播放完畢以后,進(jìn)度條再次回到原點
5當(dāng)拖滑動滑塊以后,松開滑塊,進(jìn)度條繼續(xù)走動,音頻從滑塊松開的位置播放,直至播放結(jié)束
html:
<!--進(jìn)度條-->
<viewclass="progresswrap">
<sliderclass="drag"step="10"value="{{curTimeVal}}"max="{{duration}}"
backgroundColor="#373636"activeColor="#FF1744"bindchange="slideBar"/>
</view>
<!--控制按鈕-->
<viewclass="btns">
<viewbindtap='play'><imagesrc="{{playSrc}}"></image></view>
<viewbindtap='pause'><imagesrc="{{pauseSrc}}"></image></view>
</view>
js
const innerAudioContext = wx.createInnerAudioContext();
Page({
duration:0,
curTimeVal:0,
})
onLoad: function:(){
wx.request({
url: utils.baseUrl + "/message/get?sessionID=" + sessionID + "&id=" + id,
success: function (res) {
var resData = res.data.data
var audioSrc ="https://www.rujian.vip"+resData.resourceURL;
that.setData({
contResponseArr: resData,
audioSrc: audioSrc
})
innerAudioContext.src = audioSrc;
}
})
},
play: function (e) {
var that=this;
innerAudioContext.play();
innerAudioContext.onPlay((res) =>
that.updateTime(that)
}) //沒有這個事件觸發(fā),無法執(zhí)行updatatime
}
pause:function(){
innerAudioContext.pause();
},
updateTime:function(that){
innerAudioContext.onTimeUpdate((res) => {
//更新時把當(dāng)前的值給slide組件里的value值。slide的滑塊就能實現(xiàn)同步更新
console.log("duratio的值:", innerAudioContext.duration)
that.setData({
duration: innerAudioContext.duration.toFixed(2) *100,
curTimeVal: innerAudioContext.currentTime.toFixed(2) *100,
})
})
//播放到最后一秒
if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
that.setStopState(that)
}
innerAudioContext.onEnded(() => {
that.setStopState(that)
})
},
//拖動滑塊
slideBar:function(e){
let that=this;
var curval=e.detail.value; //滑塊拖動的當(dāng)前值
innerAudioContext.seek(curval); //讓滑塊跳轉(zhuǎn)至指定位置
innerAudioContext.onSeeked((res)=>{
this.updateTime(that) //注意這里要繼續(xù)出發(fā)updataTime事件,
})
},
setStopState:function(that){
that.setData({
curTimeVal: 0
})
innerAudioContext.stop()
}
效果如下: