鸿蒙做一个类似抖音视频demo

自己练习顺便记录一下
先设置好界面如下

    build() {
    Row() {
      Column() {
        Swiper() {
          ForEach(allData, (item: VideoItem, index: number) => {
            VideoComp({
              item,
              index,
              currentIndex: this.currentIndex
            })
          })
        }
        .vertical(true)
        .index($$this.currentIndex)
        .cachedCount(3)
        .indicator(false)
        .width('100%')
        .height('100%')
      }
      .width('100%')
    }
    .height('100%')
  }

里面的用到了VideoItem是一个对象数组,所以需要定义一下对象和数据

class VideoItem {
  videoUrl: string = ''
  title: string = ""
}

对象也可以重新创建一个文件然后导出后使用,但是小练习就没有重新创建,之后就是从VideoItem中拿出title和videoUrl地址,这里的路由自己从网上找就行


const allData: VideoItem[] = [
  {
    title:'标题',
    videoUrl:'视频链接'
  }
]

然后就是创建一个VideoComp组件

@Component
struct VideoComp {
  @Require
  @Prop
  item: VideoItem
  controller: VideoController = new VideoController()
  index: number = -1
  @Require
  @Prop
  @Watch('changPlay')
  currentIndex: number

  //根据index确定当前的视频播放其他视频停止
  changPlay() {
    this.currentIndex === this.index ? this.controller.start() : this.controller.pause()
  }

  @State
  isPlay: boolean = true

  build() {
    Stack({ alignContent: Alignment.Bottom }) {
      Video({
        src: this.item.videoUrl,
        controller: this.controller
      })
        .controls(false)//不展示控制条
        .objectFit(ImageFit.Contain)
        .autoPlay(this.index === this.currentIndex)//视频是否自动播放
        //判断视频是否停止
        .onClick(() => {
          this.isPlay ? this.controller.pause() : this.controller.start()
        })
        //暂停视频
        .onPause(() => {
          this.isPlay = false
        })
        //播放视频
        .onStart(() => {
          this.isPlay = true
        })
      //当视频没有播放时展示图片
      if (!this.isPlay) {
        Image($r('sys.media.ohos_ic_public_play'))
          .width('40%')
          .fillColor('#deeeee')
          //当点击图片时开始播放
          .onClick(() => {
            this.controller.start()
          })
      }
      Text(this.item.title)
        .fontSize(14)
        .fontColor('#fff')
        .padding(20)
    }
  }
}

忘了这个 @State currentIndex: number = 0 这个需要在声明一下,用来校验当前视频是否播放

完事,小demo结束~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值