带有avplayerviewcontroller播放控件的AVPlayer

AVPlayer with playback controls of avplayerviewcontroller

我将 n avplayer 放在视图控制器中以自定义视图控制器的一些其他元素,但我仍然想要 AVPlayerViewController 中使用的播放和擦除控件。当我不使用 AvPlayerViewcontroller 时,有没有办法为 Avplayer 启用这些控件?

没有。通常的解决方案(Apple 明确建议)是使用 AVPlayerViewController 作为嵌入式视图控制器 - 即,使您的视图控制器成为自定义父视图控制器,而 AVPlayerViewController 是其子视图,现在您可以放置​​它的视图(电影和控件) 在您的视图中作为子视图井井有条。示例(self 是您的视图控制器):

let url = // whatever
let player = AVPlayer(URL:url)
let avPlayerViewController = AVPlayerViewController()
avPlayerViewController.player = player
avPlayerViewController.view.frame = // whatever
self.addChild(avPlayerViewController)
self.view.addSubview(avPlayerViewController.view)
avPlayerViewController.didMove(toParent: self)

要将此 post 更新为 Swift 5,您可以尝试此代码:

let videoURL = URL(string: "https://your_video_in_internet.mp4")
let player = AVPlayer(url: videoUrl)
let playerViewController: AVPlayerViewController!
playerViewController = AVPlayerViewController()
playerViewController.view.frame = YOUR_FRAME_OR_EMBED_IN_STORYBOARD
playerViewController.player = player
playerViewController.showsPlaybackControls = true
playerViewController.videoGravity = .resizeAspectFill
YOUR_FRAME_OR_EMBED_IN_STORYBOARD.addSubview(playerViewController.view)
playerViewController.player!.play()  
let player = AVPlayer(url: url)    
let playerViewController = AVPlayerViewController()
playerViewController.view.frame = self.videoPlayerView.bounds
playerViewController.player = player
self.addChild(playerViewController)
self.videoPlayerView.addSubview(playerViewController.view)
playerViewController.didMove(toParent: self)