xcode Swift 将录制的视频保存为 mov 或 mp4
Posted
技术标签:
【中文标题】xcode Swift 将录制的视频保存为 mov 或 mp4【英文标题】:xcode Swift Save Recorded Video as mov or mp4 【发布时间】:2016-01-20 05:33:05 【问题描述】:我一直在寻找一种使用 AVCaptureSession 保存录制视频的方法
这是我的代码:
@IBOutlet weak var tv: UIView!
var session:AVCaptureSession?
var output: AVCaptureVideoDataOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var out:AVCaptureMovieFileOutput!
var outPath:NSURL?
...关于视图 didload 函数
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let filemgr = NSFileManager.defaultManager()
let documentsURL = filemgr.URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask)[0]
outPath = documentsURL.URLByAppendingPathComponent("temp")
session = AVCaptureSession()
session!.sessionPreset = AVCaptureSessionPresetLow
let camera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var deviceInput:AVCaptureDeviceInput?
do
try deviceInput = AVCaptureDeviceInput(device: camera)
catch
session?.addInput(deviceInput)
previewLayer = AVCaptureVideoPreviewLayer(session: session)
let frame = CGRect(x: 0, y: 0, width: self.tv.frame.width, height: self.tv.frame.height)
tv.layer.addSublayer(previewLayer!)
previewLayer?.frame = frame
session?.startRunning()
录制按钮操作
let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self
out = AVCaptureMovieFileOutput()
session?.addOutput(out)
out.startRecordingToOutputFileURL(outPath, recordingDelegate: recordingDelegate)
...停止按钮操作
out.stopRecording()
..和委托功能
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outPath: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!)
print("record fin")
return
func captureOutput(captureOutPut: AVCaptureFileOutput!, didStartRecordingTOOutputFileAtURL outPath: NSURL!, fromConnections connections: [AnyObject]!)
print("record start")
return
感谢您的帮助:)
编辑: 以下是一些额外的细节
代码中没有错误或警告,应用运行良好 相机预览显示,但问题在于保存录制的视频,当调用 out.startRecordingToOutputFileURL(outPath, recordingDelegate: recordingDelegate) 时,它不保存任何文件
【问题讨论】:
你的代表被叫到了吗? 是的,正在调用委托函数 【参考方案1】:如果有人碰巧遇到和我一样的问题,这里是解决方案
在委托函数 didfinishrecording 中添加这段代码
let library = phphotoLibrary.sharedPhotoLibrary()
library.performChanges(
PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(outPath)!
, completionHandler: success, error in
NSLog("Finished saving asset. %@", (success ? "Success." : error!))
)
问候
【讨论】:
以上是关于xcode Swift 将录制的视频保存为 mov 或 mp4的主要内容,如果未能解决你的问题,请参考以下文章