Search code examples
swifttvos

Local Video File loop tvOS


I'm attempting to play a simple local clip in Xcode7 using Swift for tvOS. All I want is for the video to load fullscreen in the view and loop. Every tutorial I see has the old MPMoviePlayerController or loads from a URL. What is the best way to do this on tvOS?

Update2: This got the video to loop but there is a pause in between. looking into it now to see how to do it seamlessly.

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()
    }




}

Solution

  • Let's say your file is named video.m4v and is stored locally on the device (don't forget to add it to Copy Bundle Resources in Build Phases). Create a stored property so you can access the AVPlayer-instance:

    var videoPlayer: AVPlayer?
    

    Setup the video player and add the AVPlayerLayer to your view hierarchy.

    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)
    }
    

    You have now subscribed a notification that i sent when this video ends. Implement handler and tell the player to replay video.

    func playerDidReachEnd(notification: NSNotification) {
        self.videoPlayer.seekToTime(kCMTimeZero)
        self.videoPlayer.play()
    }