实例:一个简单的播放器效果。
实现的功能:
1点击播放按钮。音频开始播放。
2播放的同时,进度条在不停的更新走动
3点击暂停按钮,音频停止播放
4当音频播放完毕以后,进度条再次回到原点
5当拖滑动滑块以后,松开滑块,进度条继续走动,音频从滑块松开的位置播放,直至播放结束
html:
<!--进度条-->
<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)
}) //没有这个事件触发,无法执行updatatime
}
pause:function(){
innerAudioContext.pause();
},
updateTime:function(that){
innerAudioContext.onTimeUpdate((res) => {
//更新时把当前的值给slide组件里的value值。slide的滑块就能实现同步更新
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; //滑块拖动的当前值
innerAudioContext.seek(curval); //让滑块跳转至指定位置
innerAudioContext.onSeeked((res)=>{
this.updateTime(that) //注意这里要继续出发updataTime事件,
})
},
setStopState:function(that){
that.setData({
curTimeVal: 0
})
innerAudioContext.stop()
}
效果如下:
请发表评论