鸿蒙avplayer切换播放源地址遇到的一个问题

85 阅读1分钟

在avplayer切换播放源的时候

若不添加settimeout,会导致avplayer.url值更新不同步,依旧为上一个视频的URL导致视频卡住不播放 可能是reset()未完成就对URL进行了赋值导致的

Text('切换').width('100%').height('48lpx').onClick(()=>{
  if(this.avPlayer) {
    this.avPlayer.pause()
    this.avPlayer?.reset()
    this.currentIndex = this.currentIndex == 0 ? 1 : 0
    this.videoSrc = this.currentIndex==0 ? 'https://xxx.xxxx.cn/1754290062284.mp4?t=1757323727689' : 'https://xxx.xxxx.cn/66daa0349851.mp4?t=1757323779273'
    setTimeout(()=>{
      this.PlayVideo()
    },100)
  }
})
PlayVideo() {
  if(this.avPlayer) {
    this.avPlayer.url = this.videoSrc
    console.log('切换后的视频地址1', this.currentIndex, this.videoSrc)
    console.log('切换后的视频地址2', this.currentIndex, this.avPlayer.url)
    this.DoPlay()
  }
}
async DoPlay(){
  let mp = this.avPlayer
  console.log('zzz=== 视频地址',mp?.url)
  console.log('zzz=== doPlay方法',`mp状态:${mp?.state};url-${this.videoSrc}`)
  if (mp?.state && (mp?.state == "prepared" || mp?.state == "paused" || mp?.state == "completed" || mp?.state == "playing")) {
    mp.play()
  } else {
    // ToastUtil.showToast('视频播放出现了点问题')
  }
}