实现思路如下:
完整示例代码如下:
class VideoClass { // 创建视频类
controller: VideoController = new VideoController();
videoSrc: Resource = $rawfile('videoTest.mp4');
}
@Entry
@Component
struct VideoAutomaticallyPlays {
private swiperController: SwiperController = new SwiperController();
private videoList: Array<VideoClass> = [];
@State isShow: boolean = true; // 控制暂停按键的显隐
@State lastShow: number = 0;
aboutToAppear(): void {
for (let i = 0; i < 10; i++) {
this.videoList.push(new VideoClass()); // 创建视频实例
}
}
build() {
Column() {
Swiper(this.swiperController) {
ForEach(this.videoList, (item: VideoClass) => {
Stack() {
Video({
src: item.videoSrc,
controller: item.controller
})
.height('100%')
.width('100%')
.controls(false) // 关闭视频控制栏
.onFinish(() => {
this.swiperController.showNext(); // 跳转下个视频
});
Row() {
Column() {
Text('@XXX')
.fontColor(Color.White);
}
.height('100%')
.justifyContent(FlexAlign.End)
.padding({
bottom: 60
});
Column({ space: 40 }) {
Image($r('app.media.love'))
.width(30)
.height(30);
Image($r('app.media.comment'))
.width(30)
.height(30);
Image($r('app.media.share'))
.width(30)
.height(30);
}
.height('100%')
.justifyContent(FlexAlign.End)
.padding({
bottom: 150
});
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding({
left: 20,
right: 20
});
Image($r('app.media.play'))
.width(30)
.height(30)
.visibility(this.isShow ? Visibility.Visible : Visibility.None); // 是否显示暂停图标
}
.onClick(() => { // 点击切换视频播放状态
if (this.isShow) {
item.controller.start(); // 开始播放
} else {
item.controller.pause(); // 暂停播放
}
this.isShow = !this.isShow;
});
});
}
.width('100%')
.height('100%')
.indicator(false)
.vertical(true)
.loop(false)
.autoPlay(false)
.onChange((index: number) => { // 页面切换时触发的回调
this.videoList[this.lastShow].controller.stop();
this.videoList[index].controller.start(); // 启动视频播放
this.lastShow = index;
this.isShow = false;
});
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center);
}
}