
回复
今天要跟大家分享幽蓝君开发的第二个三方库,一个视频播放器组件:ylplayer,贴个效果图:
这款播放器是基于系统的Video组件进行开发,因为Video自带的工具栏我觉得不太美观,还有就是它的全屏功能有一些问题,无法做到自动横屏。针对这些痛点做了一些优化,希望能做一款美观、丝滑、好用的视频播放器。
下面分享一下ylplayer的实现过程。
首先要把Video的工具栏隐藏,换上我们自定义的标题和工具栏,这里用到层叠布局,自定义的工具栏使用透明度属性来控制它的隐藏和显示:
Stack({alignContent:Alignment.Bottom}) {
Video({
src: this.videoSrc,
controller: this.controller,
previewUri:this.previewUri,
})
.onPrepared((duration)=>{
//duration表示总时长
})
.onUpdate((e?: ESObject) => {
// e.time表示当前播放位置
})
.width(this.isLandscapeStart?this.screen_width * 16 / 9:'100%')
.height(this.isLandscapeStart?this.screen_width:this.screen_width * 9 / 16)
//关闭自动播放
.autoPlay(false)
//隐藏控制栏
.controls(false)
.objectFit(ImageFit.Cover)
.loop(false)
//标题和工具栏部分
Column(){
}
//透明度,点击视频设置工具栏的显示和隐藏
.opacity(this.alpha)}
Video组件的控制器提供了一些方法,比如start()、pause()、stop()等来控制视频的播放和停止等等,这里不再赘述。主要说一下进度条,进度条包括总时长、当前播放时间和控制条三部分,两个时间可以在Video的回调方法中获取到,上面的代码已经提到。
对于中间的控制条,系统的Progress组件虽然功能比较丰富,但是它没有中间的圆点,所以这里也需要自定义:
Stack({alignContent:Alignment.Start}){
Row(){
}
.width('100%')
.height(4)
.borderRadius(2)
.backgroundColor('rgba(100,100,100,0.7)')
Row(){
Row()
.width(this.paning?this.offsetX:this.positionX)
.height(4)
.borderRadius(2)
.backgroundColor(Color.White)
Row(){
}
.width(15)
.height(15)
.borderRadius(7.5)
.backgroundColor(Color.White)
.margin({left:-7})
.gesture(
// 绑定拖动手势
PanGesture()
.onActionStart((event: GestureEvent|undefined) => {
console.info('Pan start');
this.paning = true
})
// 当触发拖动手势时,根据回调函数修改组件的布局位置信息
.onActionUpdate((event: GestureEvent|undefined) => {
if(event){
this.offsetX = this.positionX + event.offsetX;
if(this.offsetX >= this.progressWidth){
this.offsetX = this.progressWidth
}
if(this.offsetX <= 0){
this.offsetX = 0
}
let rate = this.offsetX/this.progressWidth
let miao = Math.round(this.total* rate)
this.valueChangeUpdate(miao)
}
})
.onActionEnd(() => {
this.paning = false
this.positionX = this.offsetX;
if(this.positionX >= this.progressWidth){
this.positionX = this.progressWidth
}
if(this.positionX <= 0){
this.positionX = 0
}
this.pvalue = Math.round(this.total*this.positionX/this.progressWidth)
this.valueChangeEnd(this.pvalue)
})
)
}
}
.id('ylprogress')
.height(15)
全屏功能不仅要让视频占满屏幕,还要进行横屏设置,所以这里并不采用Video组件提供的全屏方法,而是动态设置视频的尺寸和位置,同时设置应用横屏:
this.windowClass.setPreferredOrientation(window.Orientation.USER_ROTATION_LANDSCAPE
).then(() => {
}).catch((err: BusinessError) => {
});
以上就是大概的实现过程,ylplayer已经上传到ohpm仓库,大家可以直接在终端安装使用:
ohpm install @youlanjihua/ylplayer
import { ylplayer } from '@youlanjihua/ylplayer'
ylplayer({videoSrc:this.videoUrl,title:'这是标题,可以不传',previewUri:'这是封面,可以不传'})