AVPlayer无法加载通过xcode重新运行应用程序后保存的.mov文件

时间:2017-06-08 11:07:26

标签: swift avfoundation avplayer avplayerviewcontroller avplayeritem

我有这个应用程序,其主要目的是使用AVFoundation录制视频,然后保存outputfile委托。

在第一次正常运行时,应用程序可以正确记录并保存视频,我可以将生成的输出文件URL加载到我在下一个viewcontroller上的Avplayer中。

如果不重新运行Xcode,AVPlayer会正常播放。重新运行的意思是再次点击Command + R或点击xcode上的Play按钮重建重新运行。

当我再次运行应用程序时会发生什么,我仍然可以看到文件并通过打印列出它们,但是当我尝试访问录制的文件时,应用程序将不再播放视频。看起来视频没有正确加载或任何东西,即使它已经提前工作。在这种情况发生后,我仍然可以继续录制新录制的新录制内容,但不播放旧文件。

重建应用程序之前的旧文件在AVPlayer this is how it would look, I just took it from another stackoverflow which shows the same view but the problem is different

上看起来就像这样

AVPlayer也会在我的观察者身上成功返回.readyToPlay状态。

我很困惑应该如何解决这个问题。

if let videoPreviewController = storyBoard.instantiateViewController(withIdentifier: "VideoPreviewController") as? VideoPreviewController {


                    let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")
                    videoPreviewController.player = AVPlayer()
                    let playerItem = AVPlayerItem.init(url: url as URL)
                    videoPreviewController.player?.replaceCurrentItem(with: playerItem)

                    videoPreviewController.report = relationship
                    videoPreviewController.appointment = self.appointment
                    navigation.pushViewController(videoPreviewController, animated: true)
                }

1 个答案:

答案 0 :(得分:2)

你的问题就在这一行:

  let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")

每次重新启动应用时,该路径都会发生变化 - 您无法对其进行硬编码。您必须向操作系统询问文档文件夹的路径并将文件名附加到其中。

let userDocumentsURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileName = "Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov"

let movieURL = userDocumentsURL.appendingPathComponent(fileName)

顺便说一句,这可能是你首先保存文件的方式......获取路径,附加文件名并保存。