具体实现代码可参考该指南。
@Entry
@Component
struct VideoAutoPlayByVisibility {
@State videoUrl: ResourceStr = $rawfile('video1.mp4'); // 替换为您的本地视频文件路径
controller: VideoController = new VideoController();
build() {
Scroll() {
Column() {
Video({
src: this.videoUrl,
controller: this.controller
})
.width('100%')
.height(300)
.autoPlay(false)
.controls(true)
.loop(false)
.objectFit(ImageFit.Contain)
.onVisibleAreaApproximateChange({ ratios: [0.5], expectedUpdateInterval: 200 },
(isExpanding: boolean, currentRatio: number) => {
console.info(`Test Video isExpanding: ${isExpanding}, currentRatio: ${currentRatio}`);
// 可见比例逐渐变大,并超过一半,开始播放
if (isExpanding && currentRatio >= 0.5) {
this.controller.start();
}
// 可见比例逐渐变小,并小于一半,暂停播放
if (!isExpanding && currentRatio <= 0.5) {
this.controller.pause();
}
});
Row().width('100%').backgroundColor('#ffb3afbc').height(300);
Row().width('100%').backgroundColor('#ff87848d').height(300);
Row().width('100%').backgroundColor('#ff59575d').height(300);
};
}
.width('100%');
}
}