当从集合视图切换视频时,Swift播放器冻结但音频仍可在后台运行

时间:2018-03-05 02:05:19

标签: ios swift uicollectionview avplayer

这是我的意思的快速视频:https://youtu.be/Ld8apahZBIg

我有一个集合视图,当我点击任何第一个视频播放时,它会完美显示。当我单击返回以关闭播放器/视图以播放不同的视频时,音频在后台运行,但视频显示在播放视频时似乎会冻结。

这里是UICollectionView的相关代码:

ln -s /Library/Frameworks/R.framework/Resources/library/Rserve/libs/Rserve /Library/Frameworks/R.framework/Resources/bin/Rserve

这是我的avPlayer View Controller类的相关代码:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

       override func viewDidLoad() {
    super.viewDidLoad()
         collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)

    collectionView?.register(HomeControllerHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HomeControllerHeaderId")
   }

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return posts.count
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell
    //        self.hpc = cell
    cell.post = posts[indexPath.item]
    return cell
} 

var avPlayerViewController = VideoPlayerViewController()

var avPlayer = AVPlayer()
var playerLayer: AVPlayerLayer!

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let links = posts[indexPath.row]
    guard let url = NSURL(string: links.videoUrl) else { return }
    var player = avPlayerViewController.player
    player = AVPlayer(url: url as URL)
    let playerItem = AVPlayerItem(url: url as URL)
    avPlayer.replaceCurrentItem(with: playerItem)
    let playerController = avPlayerViewController
    playerController.player = player

self.navigationController?.pushViewController(playerController, animated: true)
        playerController.player.play()

      }
}

如果您有任何其他问题,请与我们联系。

1 个答案:

答案 0 :(得分:0)

修正了它。问题是我打电话给播放器一次显示视频。每当我尝试删除子图层并播放新视频时,视频播放器都会冻结,因为播放器图层只会加载一次,然后当尝试播放新的播放器图层时,它不会因为需要再加载。每次显示视图控制器时,我都使用viewDidAppear来加载东西。

       grid.getChildren().remove(element);