如何使用AVPlayer从文档目录播放视频文件

4

我正在创建一个iOS视频播放器应用程序,如果我将MP4文件存储在捆绑资源中或者使用流媒体URL,它都可以正常工作。但是,如果我将文件存储在文档目录中并尝试使用AVPlayer播放,它就无法播放。我应该如何处理文档目录中的离线文件呢?

代码:

let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/myvideo.mp4"))
   self.playVideo(filePath: destinationURLForFile.path)


   func playVideo(filePath:String)
    {
        var playerItem = AVPlayerItem.init(url:URL.init(string: filePath)!)

        var player = AVPlayer(playerItem: playerItem)
        var playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.frame
        self.view.layer.addSublayer(playerLayer)
        player.play()

    }
3个回答

5

尝试这个,用Swift 3.0编写的。

let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let path = docsurl.appendingPathComponent("myvideo.mp4")
playVideo(filePath: path)

func playVideo(filePath:String)
{
    var playerItem = AVPlayerItem(url: URL(fileURLWithPath: filePath)
    var player = AVPlayer(playerItem: playerItem)
    var playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    self.view.layer.addSublayer(playerLayer)
    player.play()

}

两者相同,没有区别。 - skyshine
你错过了在问题中检索“文档路径”的代码行。 - AshokPolu
playVideo(filePath: path) 替换为 playVideo(filePath: path.path) - Chirag D jinjuwadiya

3

Swift 3/4 可以完美使用

打开录像机

@IBAction func RecordAction(_ sender: Any) {

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
            print("CameraAvailable")
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            imagePicker.mediaTypes = [kUTTypeMovie as String]
            imagePicker.allowsEditing = false
            imagePicker.showsCameraControls = true

            self.present(imagePicker,animated: true, completion: nil)
        }

        else{
            print("CameraNotAvailable")
        }
    }

保存到文档目录

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // recover video URL
        let url = info[UIImagePickerControllerMediaURL] as? URL
        // check if video is compatible with album
        let compatible: Bool = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum((url?.path)!)
        // save
        if compatible {
            UISaveVideoAtPathToSavedPhotosAlbum((url?.path)!, self, nil, nil)
            print("saved!!!! \(String(describing: url?.path))")

        }
        videopath = url //save url to send next function play video
        dismiss(animated: true, completion: nil)
    }
//   error
    func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) {
    }

从文档目录播放视频
 @IBAction func playvideo(_ sender: Any)
    {
        let player = AVPlayer(url: videopath!)  // video path coming from above function

        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
}

3

我尝试了上述几种方法,但发现每次启动应用程序时,文档路径都会更改,这会更改URL的第一部分。

这帮助我获取了文件的当前位置:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let playerItem = AVPlayerItem(url: URL(fileURLWithPath: documentsPath.appendingFormat("/\(clipId).mp4")))
player = AVPlayer(playerItem: playerItem)

它有效了,这实际上非常聪明,你帮了我,谢谢。我看到你有clipId,我猜你正在制作一个视频应用程序,无论如何,我正在尝试回报帮助,你想要一个URL,它会给你JSON响应,并提供YouTube视频URL下载链接,我会给你的,非常感谢。 - Abd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接