使用 tvOS 从本地文件播放视频

Play video from local file with tvOS

我想在 Apple TV 上打开我的应用程序时播放一段小视频(20 秒)。但是我找不到如何从本地文件实现 URL。

这是我目前所知道的,但不幸的是它不起作用:

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

    }

您的代码看起来不错。也许,你应该试试这个:

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.

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

我想列出最紧凑的方式以及所有四个障碍:

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