我尝试使用Swift for tvOS在Xcode7中播放一个简单的本地剪辑。我想要的只是视频在视图和循环中加载全屏。我看到的每个教程都有旧的MPMoviePlayerController
或从URL加载。在tvOS上执行此操作的最佳方法是什么?
Update2:这让视频循环播放,但两者之间有一个暂停。现在调查一下,看看如何无缝地完成它。
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var videoPlayer: AVPlayer!
var playerLayer: AVPlayerLayer?
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")
let url = NSURL(fileURLWithPath: path!)
let playerItem = AVPlayerItem(URL: url)
self.videoPlayer = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: self.videoPlayer)
self.playerLayer!.frame = self.view.frame
self.videoPlayer!.play()
self.view.layer.addSublayer(self.playerLayer!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerDidReachEnd:"), name: AVPlayerItemDidPlayToEndTimeNotification, object:nil)
}
func playerDidReachEnd(notification: NSNotification) {
self.videoPlayer.seekToTime(kCMTimeZero)
self.videoPlayer.play()
}
}
答案 0 :(得分:3)
我们假设您的文件名为video.m4v
,并存储在设备本地(不要忘记将其添加到构建阶段的复制捆绑资源)。创建一个存储的属性,以便您可以访问AVPlayer-instance
:
var videoPlayer: AVPlayer?
设置视频播放器并将AVPlayerLayer
添加到视图层次结构中。
if let path = NSBundle.mainBundle().pathForResource("video", ofType:"m4v") {
let url = NSURL(fileURLWithPath: path)
let playerItem = AVPlayerItem(URL: url)
self.videoPlayer = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: self.videoPlayer)
self.playerLayer!.frame = self.view.frame
self.view.layer.addSublayer(self.playerLayer!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerDidReachEnd:"), name: AVPlayerItemDidPlayToEndTimeNotification, object:nil)
}
您现在已订阅了此视频结束时发送的通知。实现处理程序并告诉玩家重播视频。
func playerDidReachEnd(notification: NSNotification) {
self.videoPlayer.seekToTime(kCMTimeZero)
self.videoPlayer.play()
}