发现页面使用Video、Swiper组件搭配实现短视频播放功能,不涉及与H5页面的交互。
首个视频播放完后,调用showNext()跳转下个视频,同时在Swiper的页面切换回调里调用Video组件的start()事件播放视频。以onChange事件为例:
class VideoSet { controller: VideoController = new VideoController(); videoSrc: Resource = $rawfile('videoTest.mp4'); // 需替换为实际资源 } @Entry @Component struct VideoListAutoPlayPage { private swiperController: SwiperController = new SwiperController(); private videoList: Array<VideoSet> = []; @State isShow: boolean = true; aboutToAppear(): void { for (let i = 0; i < 10; i++) { this.videoList.push(new VideoSet()); } } build() { Column() { Swiper(this.swiperController) { ForEach(this.videoList, (item: VideoSet) => { 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[index].controller.start(); // 启动视频播放 }); } .width('100%') .height('100%') .justifyContent(FlexAlign.Center); } }