2016-09-15 90 views
1

我使用以下代碼來顯示兩個不同的視頻源作爲背景。 「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

方法'seekToTime'的返回類型是'void'而不是'CMTime'。 –

回答

2

經過調查問題首先看看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() 
} 

在這種情況下,您正在跟蹤視頻何時結束,然後再次啓動。

+0

不知何故我現在又有了一個bug,我已經更新了這個問題。謝謝! – Victor