通过事件回调机制来实现。核心思路是:
父组件:
@Component
@Entry
struct MovePage {
@State duration: number = 0; // 视频总时长状态
@State time: number = 0; // 当前播放时间状态
build() {
Column({ space: 20 }) {
Column() {
Player({
src: $rawfile('example.mp4'),
isControls: true,
onPrepared: (duration: number) => {
this.duration = duration;
},
onUpdate: (time: number) => {
this.time = time;
}
});
}
.width('100%')
.height('70%');
Column({ space: 5 }) {
Text('视频总时长:' + this.duration + 's');
Text('当前播放进度:' + this.time + 's');
}.width('100%');
}
.width('100%')
.height('100%');
}
} 子组件:
@Component
export default struct Player {
@Prop src: string | Resource;
@Prop isControls: boolean = true;
onPrepared?: (duration: number) => void; // 视频准备完成时触发该事件
onUpdate?: (time: number) => void; // 播放进度变化时触发该事件
private videoController: VideoController = new VideoController();
build() {
Column({ space: 10 }) {
Video({
src: this.src,
controller: this.videoController
})
.loop(true)// 循环播放
.objectFit(ImageFit.Cover)// 画面填充模式
.controls(this.isControls)// 绑定控制条
.onPrepared((event) => {
this.onPrepared?.(event.duration); // 获取到总时长后调用
})
.onUpdate((event) => {
this.onUpdate?.(event.time); // 当前视频播放的进度
})
.onError(() => {
console.error('播放失败');
});
Row({ space: 10 }) {
Button('开始播放')
.onClick(() => {
this.videoController.start();
});
Button('暂停播放')
.onClick(() => {
this.videoController.pause();
});
};
}.width('100%')
.height('90%');
}
}