我使用AVPlayerLooper循环播放本地视频文件,但是每当我按下主屏幕按钮(应用程序进入后台)然后重新打开应用程序时,视频便停止播放。我在简单视图中也有AVPlayerLooper,而不是collectionViewCell。要解决此视图上的问题,我只需在player.play()
内调用applicationDidBecomeActive()
。这不适用于collectionViewCell。
尝试在应用进入背景之前删除playerLayer,并在应用未激活时再次添加它。
VideoView设置代码:
func setupPlayerView() {
if let videoURL = allExercises.array[currentExercise].videoLink {
if player == nil {
player = AVQueuePlayer()
player?.isMuted = true
playerLayer = AVPlayerLayer(player: player)
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.frame
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
}
theItem = AVPlayerItem(url: URL(fileURLWithPath: videoURL))
playerLooper = AVPlayerLooper(player: player!, templateItem: theItem!)
player?.play()
print("DIDSETUP")
}
}
collectionView cellForItemAt:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
currentExercise = indexPath.section
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LiveView", for: indexPath) as! HorizontalLiveViewCell
cell.nameLabel.text = allExercises.array[indexPath.section].name
return cell
}
collectionViewCell的VideoView变量:
var videoView: VideoPlayerView {
let video = VideoPlayerView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * (9 / 16)))
return video
}
一切正常,直到我单击主页按钮将应用程序发送到后台。如何重新播放视频?整个单元都可以重新加载,这没问题。