#鸿蒙通关秘籍#在鸿蒙视频播放器实现自动切换视频的功能时需要注意什么?

HarmonyOS
2024-12-02 14:14:44
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
RADIUS风谷

实现自动切换视频的功能时,可以监听播放器的 stateChange 事件。当当前视频状态变为 completed 状态时,自动获取下一个视频的索引并请求播放下一个视频。确保视频索引重置从而支持循环播放。以下是实现代码示例:

import media from '@ohos.multimedia.media'

export class VideoAVPlayerClass {
  static player: media.AVPlayer | null = null
  static duration: number = 0
  static time: number = 0
  static isPlay: boolean = false
  static playList: videoItemType[] = []
  static playIndex: number = 0
  static surfaceId: string = ''

  static async init(initParams: InitParams) {
    VideoAVPlayerClass.avPlayer = await media.createAVPlayer()
    VideoAVPlayerClass.avPlayer.on('stateChange', async (state) => {
      if (state === 'completed') {
        VideoAVPlayerClass.playIndex++
        VideoAVPlayerClass.playIndex %= VideoAVPlayerClass.playList.length
        VideoAVPlayerClass.singlePlay(VideoAVPlayerClass.playList[VideoAVPlayerClass.playIndex])
        VideoAVPlayerClass.isPlay = true
      }
    })
  }

  static singlePlay(video?: videoItemType) {
    if (video) {
      let index = VideoAVPlayerClass.playList.findIndex((item: videoItemType) => item.id === video.id)
      if (index > -1) {
        VideoAVPlayerClass.playIndex = index
      } else {
        VideoAVPlayerClass.playList.push(video)
        VideoAVPlayerClass.playIndex = VideoAVPlayerClass.playList.length - 1
      }
    }
    VideoAVPlayerClass.changePlay()
  }

  static async changePlay() {
    await VideoAVPlayerClass.avPlayer.reset()
    VideoAVPlayerClass.time = 0
    VideoAVPlayerClass.duration = 0
    VideoAVPlayerClass.avPlayer.url = VideoAVPlayerClass.playList[VideoAVPlayerClass.playIndex].url
    VideoAVPlayerClass.updateState()
  }
}
分享
微博
QQ
微信
回复
2024-12-02 15:43:47