小程序如何实现视频或音频自定义可拖拽进度条
来源:不言
发布时间:2018-10-10 16:13:20
阅读量:1429
本篇文章给大家带来的内容是关于小程序如何实现视频或音频自定义可拖拽进度条,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
小程序原生组件的音频播放时并没有进度条的显示,而此次项目中,鉴于原生的视频进度条样式太丑,产品要求做一个可拖拽的进度条满足需求。
视频和音频提供的api大致是相似的,可以根据以下代码修改为与音频相关的进度条。
wxml的结构如下:
1 2 3 4 5 6 7 | < video id = "myVideo" src = "http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400" enable-danmu danmu-btn controls = "{{false}}" autoplay = '{{true}}' bindtimeupdate = "videoUpdate" objectFit = "fill" ></ video >
< view class = 'process-container' >
< image src = '{{playStates ? "../../assets/image/pause_icon.png" : "../../assets/image/play_icon.png"}}' class = 'video-controls-icon' bindtap = 'videoOpreation' ></ image >
< view class = 'slider-container' >
< slider bindchange = "sliderChange" bindchanging = "sliderChanging" step = "1" value = "{{sliderValue}}" backgroundColor = "#A8A8A8" activeColor = "#FFEE83" block-color = "#FFEE83" />
</ view >
</ view >
|
data中初始化了sliderValue, updateState, playStates几个变量。
1 2 3 4 5 6 7 8 9 10 11 | data: {
sliderValue: 0, //控制进度条slider的值,
updateState: false, //防止视频播放过程中导致的拖拽失效
playStates: true //控制播放 & 暂停按钮的显示
},
onReady: function () {
this.videoContext = wx.createVideoContext('myVideo');
this.setData({
updateState: true
})
},
|
videoUpdate在播放进度变化时触发,触发频率 250ms 一次。event.detail = {currentTime, duration},currentTime表示当前时间,duration表示总时长,都以秒为单位。
1 2 3 4 5 6 7 8 9 | videoUpdate(e) {
if (this.data.updateState) {
let sliderValue = e.detail.currentTime / e.detail.duration * 100;
this.setData({
sliderValue,
duration: e.detail.duration
})
}
},
|
进度条可拖拽并指定视频跳转到相应的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | sliderChanging(e) {
this.setData({
updateState: false
})
},
sliderChange(e) {
if (this.data.duration) {
this.videoContext.seek(e.detail.value / 100 * this.data.duration);
this.setData({
sliderValue: e.detail.value,
updateState: true
})
}
},
|
暂停/播放视频
1 2 3 4 5 6 | videoOpreation() {
this.data.playStates ? this.videoContext.pause() : this.videoContext.play();
this.setData({
playStates: !this.data.playStates
})
},
|
总结:slider的最大值为100, step的值最小为1,这会导致视频或音频播放时间过长的时候,slider滑块移动速度很慢,拖拽移动的时间间隔较大,用户体验差。