我有一个UICollectionViewController,其中全屏单元格可以水平滚动。在每个单元格内是另一个垂直滚动的collectionView。 collectionView的标题单元格有一个AVPlayer从URL中提取视频。目前只播放音频,但视频不播放。
以下AVPlayer设置和观察者的代码与我在UICollectionViewCell之外的应用程序中使用过的许多其他代码没有问题。播放器帧大小检出,音频按预期播放和循环,因此观察者似乎正在触发。
相关代码:
var post: Post! {
didSet {
videoURL = URL(string: post.videoURL)
setupVideoObservers()
}
}
var videoURL: URL! {
didSet {
videoPlayer = AVPlayer(url: videoURL!)
}
}
@objc dynamic var videoPlayer: AVPlayer!
var videoPlayerLayer: AVPlayerLayer!
let videoContainerView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
func setupCell() {
addSubview(videoContainerView)
videoContainerView.anchor(top: topAnchor,
right: rightAnchor,
bottom: bottomAnchor,
left: leftAnchor)
videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
videoPlayerLayer.frame = frame
videoPlayerLayer.videoGravity = .resizeAspectFill
videoContainerView.layer.addSublayer(videoPlayerLayer)
}
func setupVideoObservers() {
addObserver(self, forKeyPath: "videoPlayer.currentItem.status", options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playerReachedEndOfVideo(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForegroundNotification), name: .UIApplicationWillEnterForeground, object: videoPlayer.currentItem)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "videoPlayer.currentItem.status" {
videoPlayer.play()
}
}
@objc func playerReachedEndOfVideo(notification: NSNotification) {
let seekTime = CMTime(seconds: 0, preferredTimescale: 1000)
videoPlayer.seek(to: seekTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
videoPlayer.play()
}
@objc func appWillEnterForegroundNotification() {
videoPlayer.play()
}
我遇到的没有视频的AVPlayer音频问题的所有其他SO解决方案都没有应用。如果有人有任何见解,我们将不胜感激。
提前致谢。
答案 0 :(得分:2)
我有一个非常类似的问题。在填充内容后,尝试将AVPlayerLayer
的框架设置为所需尺寸的CGRect()
。您也可以为Dispatch.Queue
进行didSet
异步调用。