我使用AVPlayer
和AVPlayerLayer
(Swift,iOS 8.2)播放本地视频,我需要在其父视图时调整AVPlayerLayer
(introPlayerLayer
)的大小(introView
)已调整大小,包括更改方向。到目前为止,我所尝试过的任何内容似乎都没有用,playerLayer
的大小和位置都不正确。
使用本地mp4视频设置AVPlayer
,并使用该播放器初始化AVPlayerLayer
。然后将该图层作为子图层添加到父视图中。
这是我的代码:
func playIntro() {
let path = NSBundle.mainBundle().pathForResource("intro", ofType: "mp4")
let url = NSURL.fileURLWithPath(path!)
let introPlayer = AVPlayer(URL: url)
introPlayer.allowsExternalPlayback = false
var introPlayerLayer = AVPlayerLayer(player: introPlayer)
introView.layer.addSublayer(introPlayerLayer)
introPlayerLayer.frame = introView.bounds
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: introPlayer.currentItem)
introView.hidden = false
introPlayer.play()
}
我应该将AVPlayerLayer
添加为UIView
的子图层,还是应该将父容器(UIView
)子类化,如“播放器视图”部分所示。 https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html。如果是这样,我将如何在Swift中编写PlayerView
子类(在Objective-C中显示)?
提前感谢您的帮助。
答案 0 :(得分:7)
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
var playerLayer: AVPlayerLayer?
playerLayer = AVPlayerLayer(player: player)
playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer!.frame = self.view.frame
self.view!.layer.addSublayer(playerLayer!)
player.play()
}
答案 1 :(得分:4)
我认为,在我自己的项目中,我能够做你想做的事。这没有子类化。这是我的代码:
override func viewWillLayoutSubviews() {
previewScene()
}
func previewScene() {
var firstAsset: AVAsset!, secondAsset: AVAsset!, thirdAsset: AVAsset!
firstAsset = MediaController.sharedMediaController.s3Shot1
secondAsset = MediaController.sharedMediaController.s3Shot2
thirdAsset = MediaController.sharedMediaController.s3Shot3
if firstAsset != nil && secondAsset != nil && thirdAsset != nil {
let assets = [firstAsset, secondAsset, thirdAsset]
var shots = [AVPlayerItem]()
for item in assets {
let shot = AVPlayerItem(asset: item)
shots.append(shot)
}
self.videoPlayer = AVQueuePlayer(items: shots)
self.playerLayer = AVPlayerLayer(player: self.videoPlayer)
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
AVPlayerItemDidPlayToEndTimeNotification, object: self.videoPlayer.items().last)
self.videoPreviewLayer.layer.addSublayer(playerLayer)
self.playerLayer.frame = self.videoPreviewLayer.bounds
}
}
答案 2 :(得分:0)
introView.layer.masksToBounds = true
也可能有帮助