【发布时间】:2017-01-08 08:54:44
【问题描述】:
我正在使用AVFoundation 录制视频,并从视频中创建了预览,当我完成录制视频时,视频正在预览中播放,但是当我使用以下方式保存视频时:
var fileName = "\(self.tField.text!).mp4"
fileName = fileName.stringByReplacingOccurrencesOfString(" ", withString: "_")
let path = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
//let originVideoFile = self.filePath
let destinationVideoFile = path.URLByAppendingPathComponent(fileName)
let data = NSData(contentsOfURL: self.filePath)
//try data!.writeToURL(destinationVideoFile!, options: [])
let fileManager = NSFileManager()
fileManager.createFileAtPath((destinationVideoFile?.path)!, contents: data, attributes: nil)
视频文件已创建,但当我想重新播放视频时无权访问此文件,但相机胶卷可以播放视频。
为了得到“filePath”,我使用的是AVFoundation的委托方法:
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
print("capture did finish")
print(captureOutput);
print(outputFileURL);
self.filePath = outputFileURL
performSegueWithIdentifier("previewVideo", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "previewVideo"{
let destination = segue.destinationViewController as! PreviewVC
destination.filePath = self.filePath
destination.videoDelegate = self.videoDelegate
}
}
并使用“prepareForSegue”传递数据
我返回一个包含所需信息的视频对象,当我想重新播放视频时,我使用集合视图的方法“didSelect”创建一个“AVPlayer”并使用文件名找到视频的路径,则文件存在但无法播放
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
videoSingleObject = videoObjects[indexPath.item]
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent(videoSingleObject.nameOfFile)!.path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
print("FILE AVAILABLE")
UISaveVideoAtPathToSavedPhotosAlbum(filePath, nil, nil, nil)
print("PATH: \(filePath)")
let videoPath = NSURL(string: filePath)!
//filePathURL = videoPath
print(videoPath)
asset = AVAsset(URL: videoPath)
playerItem = AVPlayerItem(asset: asset)
print("DURATION: \(CMTimeGetSeconds(asset.duration))")
player = AVPlayer(playerItem: playerItem)
playerViewController.player = player
self.presentViewController(playerViewController, animated: true, completion: nil)
player.play()
}else {
print("THE DIRECTORY NOT EXIST")
}
}
但我使用“UISaveVideoAtPathToSavedPhotosAlbum(filePath, nil, nil, nil)”分享cameraRoll中的视频,而cameraRoll中的视频是可以播放的。
【问题讨论】:
-
很棒的工作代码!