我使用以下代码将两个不同的视频源显示为背景。 " selectVideo" (SegmentedControl
)用于选择视频。问题出在下面。
@IBAction func selectVideo(sender: AnyObject) {
if self.Controller.selectedIndex == 1 {
self.videoBackgroundCustomer()
}
if self.Controller.selectedIndex == 0 {
self.videoBackgroundDriver()
}
}
func videoBackgroundDriver() {
//Load video background.
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("background_video_2", withExtension: "mp4")!
player = AVPlayer(URL: videoURL)
videoBackground()
}
//Video background customer
func videoBackgroundCustomer() {
//Load video background.
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("background_video_1", withExtension: "mp4")!
player = AVPlayer(URL: videoURL)
videoBackground()
}
//Vieobackground-code part 2, provides with less code.
func videoBackground() {
player?.actionAtItemEnd = .None
player?.muted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
player?.play()
//call loop video
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.loopVideo), name: AVPlayerItemDidPlayToEndTimeNotification, object: player!.currentItem)
}
//Loop video
func loopVideo() {
player?.seekToTime(kCMTimeZero)
player?.play()
}
问题:视频应在最后一个视频结束后重新启动。而不是在最近的视频结束时。
如何在上次播放视频完成后重复播放?谢谢
答案 0 :(得分:5)
在对问题进行调查后,首先查看documentation并返回方法的值。
- (void)seekToTime:(CMTime)time;
您使用返回void
但无法与CMTime
为解决您的问题,请尝试以下解决方案:
首先,您需要订阅您的通知,以指示视频已结束。
NSNotificationCenter.defaultCenter().addObserver(self,selector: "itemDidReachEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: player.currentItem)
而不是定义处理此通知的方法。
func itemDidReachEnd(notification: NSNotification) {
player.seekToTime(kCMTimeZero)
player.play()
}
在这种情况下,您正在跟踪视频何时结束并再次启动。