如何使用 avplayer 播放文档目录中的视频文件

How to play video file from documentdirectory using avplayer

我正在 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()

    }

试试这个,写在 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()

}

swift 3/4 100%%%%%%% 可行

录像机开启摄像机

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

我尝试了包括上述在内的几种方法,但发现应用程序每次启动时文档路径都会发生变化,这会改变 URL.

的第一部分

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

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