0

所以我在我的 HomeViewController 上有一个视图,我想在其中播放视频。在 viewDidLoad() 我调用 playVideo() 这是我的代码:

func playVideo() {
    guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
        debugPrint("video.mov not found.")
        return
    }

    let avPlayer = AVPlayer(url: URL(fileURLWithPath: filePath))
    let avPlayerController = AVPlayerViewController()
    avPlayerController.player = avPlayer
    avPlayerController.view.frame = playerView.bounds
    avPlayerController.showsPlaybackControls = false
    avPlayerController.player?.play()
    playerView.addSubview(avPlayerController.view)
    playerView.bringSubview(toFront: QRButton)
}

我得到的只是黑色背景,没有视频。我究竟做错了什么?我已经尝试解决这个问题一段时间了。

iOS:11.2 测试版
Xcode:9.2 测试版

4

1 回答 1

1

尝试avPlayer作为类变量使用,可能还没开始播放就已经释放了。

class ViewController: UIViewController {
     var avPlayer:AVPlayer?

    func playVideo() {
    guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
        debugPrint("video.mov not found.")
        return
    }

    avPlayer? = AVPlayer(url: URL(fileURLWithPath: filePath))
    let avPlayerController = AVPlayerViewController()
    avPlayerController.player = avPlayer
    avPlayerController.view.frame = playerView.bounds
    avPlayerController.showsPlaybackControls = false
    avPlayerController.player?.play()
    playerView.addSubview(avPlayerController.view)
    playerView.bringSubview(toFront: QRButton)
 }
} 
于 2017-11-08T19:40:05.267 回答