我目前正在使用自助服务终端应用。此功能的核心是单个电影播放器视图控制器。该应用程序将循环浏览各种电影文件,以及根据当前正在播放的电影显示UI元素的各种位置。
我在这里设置了视图控制器的avPlayer
:
func initPlayer() {
setAvPlayerItem()
avPlayerItem = AVPlayerItem(asset: avAsset)
avPlayer = AVPlayer(playerItem: avPlayerItem)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayerLayer.frame = UIScreen.main.bounds
movieView.layer.addSublayer(avPlayerLayer)
notificationCenter.removeObserver(self,
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
notificationCenter.addObserver(self,
selector: #selector(avPlayerDidPlayToEndTime),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
avPlayer.seek(to: kCMTimeZero)
avPlayer.volume = 0.0
avPlayer.play()
}
这是我播放当前电影的地方:
func playCurrentMovie() {
setAvPlayerItem()
avPlayer.replaceCurrentItem(with: avPlayerItem)
notificationCenter.removeObserver(self,
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
notificationCenter.addObserver(self,
selector: #selector(avPlayerDidPlayToEndTime),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
avPlayer.seek(to: kCMTimeZero)
avPlayer.volume = 0.0
avPlayer.play()
}
...以及我在哪里设置avPlayerAsset
应该使用的内容:
func setAvPlayerItem() {
let resource = moviesCollection[currentMovie]["Movie"] as! String?
guard let moviePath = Bundle.main.path(forResource: resource,
ofType:"mp4") else {
debugPrint("video not found")
return
}
movieURL = URL(fileURLWithPath: moviePath)
avAsset = AVAsset(url: movieURL)
avPlayerItem = AVPlayerItem(asset: avAsset)
}
这在模拟器上完美运行。在设备上运行时(iPad Pro 12.9"),每次我前进以播放新的视频资产时,屏幕上都会出现黑色闪烁。
有没有人知道为什么会出现黑色闪烁?
答案 0 :(得分:0)
为了防止这种黑色闪烁,我已经做了很多尝试,但都没有成功。但是我确实想出了一种对用户隐藏的方法。
首先,我制作了一个非常简单的视图,该视图包装了在此示例中称为AVPlayerLayer
的{{1}}。然后,我将该视图添加为视频播放器视图的子视图。然后,每当我要加载新视频时,我都会这样做:
videoView
如果您支持清除视频或其他任何内容,请确保删除if let snapshotView = playerView.snapshotView(afterScreenUpdates: false) {
insertSubview(snapshotView, belowSubview: videoView)
snapshotView.frame = videoView.bounds
}
let item: AVPlayerItem = ...
player.replaceCurrentItem(with: item)
// The rest of your loading like normal
。