O.Olivier
O.Olivier

Reputation: 240

Play video from local file with tvOS

I want to play a little video (20 seconds) when my app opens on the Apple TV. But I can't find how to implement the URL from a local file.

This is what I've got so far, but unfortunately it doesn't work:

    override func viewDidLoad() {
        super.viewDidLoad()

        // I know this is how to play a file from a webserver:
        // player = AVPlayer(URL: NSURL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)

        // But I can't find how to set the URL to a local file in the app
        let path = NSBundle.mainBundle().pathForResource("bunny", ofType:"mp4")
        let url = NSURL.fileURLWithPath(path!)
        player = AVPlayer(URL: url)

        player?.play()

    }

Upvotes: 2

Views: 1728

Answers (2)

wider-spider
wider-spider

Reputation: 515

I'd like to list the most compact way along with all four hurdles:

Import AVKit, Call the playVideo() function from viewDidAppear, watch out for the correct Bundle access and make sure the file has the correct target membership as stated by Ennio!

private func playVideo() {

    guard let path = Bundle.main.path(forResource: "video", ofType:"mov") else {
        debugPrint("video.mov not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))

    // Create a new AVPlayerViewController and pass it a reference to the player.
    let controller = AVPlayerViewController()
    controller.player = player

    // Modally present the player and call the player's play() method when complete.
    present(controller, animated: true) {
        player.play()
    }
}

Upvotes: 0

Ennio Bovyn
Ennio Bovyn

Reputation: 56

Your code seems fine. Maybe, you should try this:

In the Project Navigator select your Project Root > Your Target > Build Phases > Copy Bundle Resources. Check to see that your video is there, if not click the plus sign to add it.

Source: http://www.brianjcoleman.com/tutorial-play-video-swift/

Upvotes: 1

Related Questions