2

当我的应用在 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()

    }
4

2 回答 2

1

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

在 Project Navigator 中,选择您的 Project Root > Your Target > Build Phases > Copy Bundle Resources。检查您的视频是否存在,如果没有,请单击加号添加它。

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

于 2015-09-27T12:33:15.053 回答
0

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

导入AVKit ,从viewDidAppear调用 playVideo() 函数,注意正确的 Bundle 访问并确保文件具有 正确的目标成员身份,如 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()
    }
}
于 2019-02-14T12:19:46.207 回答