简体   繁体   中英

AvPlayer can't play video from custom path

I am trying to play video which is recorded in this path by me. But I can't play video from this path. What should I do?

let pathMovie = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/Movie.mp4")

        let fileUrl = NSURL(fileURLWithPath: pathMovie)
        self.videoFrame = view.frame
        self.fillMode = .ResizeAspectFill
        self.alwaysRepeat = true
        self.sound = true
        self.startTime = 0.0
        self.alpha = 1
        self.backgroundColor = UIColor.blackColor()
        self.contentURL = fileUrl

And this is error which I getting.

Failed: Optional(Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (-12893), NSLocalizedDescription=The operation could not be completed, NSURL=file:///var/mobile/Containers/Data/Application/.....-...-...-....-..../Documents/Movie.mp4, NSUnderlyingError=0x150a38e80 {Error Domain=NSOSStatusErrorDomain Code=-12893 "(null)"}})

You can play video from custom path by adding following two methods :

Note : Please pass your video name as argument for getCustomVideoPath method.

Swift 4

func getCustomVideoPath(name: String) -> String {
    let strDocumentDirectory = self.getDocumentDirectoryPath()
    return "\(strDocumentDirectory)/\(name).mp4"
}

func getDocumentDirectoryPath() -> String {
    let arrPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    return arrPaths[0]
}

//----------------------------------------------------------------

func playCustomVideo() {
    let strVideoPath = self.getCustomVideoPath(name:"Movie")
    let urlVideoPath = URL(fileURLWithPath: strVideoPath)
    let newPlayerItem = AVPlayerItem(url: urlVideoPath)
    self.avPlayer = AVPlayer(playerItem: newPlayerItem)
    avPlayerController.player = self.avPlayer
    self.avPlayer?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(rawValue: 0), context: MPPlayableContentManagerContext.observationInfo())
    self.present(avPlayerController, animated: true) {
        self.avPlayer?.play()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM