使用AVFoundation捕获视频在启动后立即停止,仅生成单个图像而不是视频

时间:2016-01-29 19:02:51

标签: ios video avfoundation avcapturesession

下面的代码应该捕获一个视频,但它只捕获一个图像。通过查看其他SO帖子和Apple文档将它拉到一起。

“视频”会在开始后立即停止录制,生成单个图像 - 即使在代码中也不应该停止,直到按下按钮。

类文档似乎没有暗示有一个“模式”属性需要翻转才能拍摄视频而不是图像,所以缺少什么?

private func initCamera() {
    captureSession.sessionPreset = AVCaptureSessionPresetHigh
    let devices = AVCaptureDevice.devices()
    for device in devices {
        if (device.hasMediaType(AVMediaTypeVideo)) {
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    beginSession()
                }
            }
        }
    }
}


func beginSession() {
    do {
        try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
    } catch {
        print("Error creating AVCaptureDeviceInput: \(error)")
    }

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    previewLayer!.frame = cameraView.layer.frame
    cameraView.layer.insertSublayer(previewLayer!, atIndex: 0)
    previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    captureSession.addOutput(videoFileOutput)
    captureSession.startRunning()
}


@IBAction func captureButtonTapped(sender: UIButton) {
    if (videoFileOutput.recording) {
        videoFileOutput.stopRecording()
        return
    }

    // If here, start recording
    let tempFilename = getUniqueFilename(".mov", numChars: 15)
    let tempPath = NSTemporaryDirectory().stringByAppendingFormat("/\(tempFilename)") as String
    let fileURL = NSURL(fileURLWithPath: tempPath)
    videoFileOutput.startRecordingToOutputFileURL(fileURL, recordingDelegate: self)
}


func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
    print("Finished recording @ \(outputFileURL)")

    // Create player & layer
    playerItem = AVPlayerItem(URL: outputFileURL)
    player = AVPlayer(playerItem: playerItem!)
    playerLayer = AVPlayerLayer(player: player)
    playerLayer!.frame = playerView.frame
    playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    playerView.layer.insertSublayer(playerLayer!, atIndex: 0)
}


func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
    print("Started recording")
}

1 个答案:

答案 0 :(得分:0)

关键是捕获captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!)中的错误,其中显示存在磁盘空间问题。