iOS Swift 2 录制视频 AVCaptureSession

2024-02-10

我创建了一个 AVCaptureSession 并将前置摄像头附加到它

do {
   try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
   }catch{print("err")}

现在我想开始和停止记录触摸事件。我该怎么做呢?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("touch")
        //Start Recording
    }

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("release");
        //End Recording and Save
    }

你没有提到你是否正在使用AVCaptureMovieFileOutput or AVCaptureVideoDataOutput作为会话的输出。前者非常适合快速录制视频,无需进一步编码,后者通过获取大块用于更高级的录制CMSampleBuffer在录音期间。

对于这个答案的范围,我会选择AVCaptureMovieFileOutput,这是一些极简的起始代码:

import UIKit
import AVFoundation
import AssetsLibrary

class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

var captureSession = AVCaptureSession()

lazy var frontCameraDevice: AVCaptureDevice? = {
    let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]
    return devices.filter{$0.position == .Front}.first
}()

lazy var micDevice: AVCaptureDevice? = {
    return AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
}()

var movieOutput = AVCaptureMovieFileOutput()

private var tempFilePath: NSURL = {
    let tempPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("tempMovie").URLByAppendingPathExtension("mp4").absoluteString
    if NSFileManager.defaultManager().fileExistsAtPath(tempPath) {
        do {
            try NSFileManager.defaultManager().removeItemAtPath(tempPath)
        } catch { }
    }
    return NSURL(string: tempPath)!
}()

private var library = ALAssetsLibrary()


override func viewDidLoad() {
    super.viewDidLoad()
    //start session configuration
    captureSession.beginConfiguration()
    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    // add device inputs (front camera and mic)
    captureSession.addInput(deviceInputFromDevice(frontCameraDevice))
    captureSession.addInput(deviceInputFromDevice(micDevice))

    // add output movieFileOutput
    movieOutput.movieFragmentInterval = kCMTimeInvalid
    captureSession.addOutput(movieOutput)

    // start session
    captureSession.commitConfiguration()
    captureSession.startRunning()
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("touch")
    // start capture
    movieOutput.startRecordingToOutputFileURL(tempFilePath, recordingDelegate: self)

}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("release")
    //stop capture
    movieOutput.stopRecording()
}

private func deviceInputFromDevice(device: AVCaptureDevice?) -> AVCaptureDeviceInput? {
    guard let validDevice = device else { return nil }
    do {
        return try AVCaptureDeviceInput(device: validDevice)
    } catch let outError {
        print("Device setup error occured \(outError)")
        return nil
    }
}

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

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
    if (error != nil)
    {
        print("Unable to save video to the iPhone  \(error.localizedDescription)")
    }
    else
    {
        // save video to photo album
        library.writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: { (assetURL: NSURL?, error: NSError?) -> Void in
            if (error != nil) {
                print("Unable to save video to the iPhone \(error!.localizedDescription)")
            }
            })

        }
    }
}

有关相机捕捉的更多信息,请参阅WWDC 2014 - 第 508 场会议 https://developer.apple.com/videos/play/wwdc2014/508/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS Swift 2 录制视频 AVCaptureSession 的相关文章

  • iOS 上的 UIBezierPath 操作

    我从一条直线开始 我希望用户能够触摸并拖动该线 使其弯曲 实际上 他们有能力将线条操纵成波浪形状 我不确定从技术上实现这一目标的最简单方法 我首先创建了三次曲线的 UIBezierPaths 数组 目的是操纵控制点 但似乎一旦绘制了 UIB
  • ios7 navigationController PushViewController 动画错误

    看来我在 navigationController PushViewController 方法中发现了一个错误 为了重新创建它 我采用了示例主详细信息项目并对 didSelectRow method void tableView UITab
  • AVCaptureSession 具有多个方向问题

    我正在尝试实现条形码扫描仪 我有一个 AVCaptureSession 它从 AVCaptureDevice 接收视频 我想支持所有方向 使用以下代码 当我运行应用程序时 纵向一切正常 然而 在横向方向上 视图会旋转 但视频输入不会旋转 所
  • 在 IOS 上使用 AVComposition 混合两个音频文件

    我正在尝试混合两个音频文件 将一个音频文件放在另一个音频文件之上 不是缝合在一起 但我在 IOS 上学习 AVFoundation 时遇到了困难 我在这里遵循了这个答案 如何使用 AVMutableCompositionTrack 合并音频
  • Swift Codable 将空 json 解码为 nil 或空对象

    这是我的代码 class LoginUserResponse Codable var result String var data LoginUserResponseData var mess String public class Log
  • 用于字数计算的 Swift String 中的字数

    我想做一个程序来找出字符串中有多少个单词 用空格 逗号或其他字符分隔 然后把总数加起来 我正在制作一个平均计算器 所以我想要数据总数 然后将所有单词相加 update Xcode 10 2 x Swift 5 或更高版本 使用基础方法enu
  • Objective-c 中的块递归

    当执行涉及 Objective C 块的递归时 我在 iOS 应用程序中收到 EXC BAD ACCESS 信号 这是简化的代码 void problematicMethod FriendInfo friendInfo onComplete
  • 自定义 UITableViewCell 选择样式?

    当我点击我的UITableViewCell 当我单击单元格时 背景部分 我的背景图像未覆盖的区域 会变成蓝色 另外 所有的UILabel单击时单元格上的 s 变为白色 这就是我想要的 然而 我不想要的是当我点击它时的蓝色背景 但如果我这样做
  • 为什么我不能在 Realm 属性上使用 private

    我正在尝试在 RealmSwift 中存储一个枚举案例 但 Realm 不支持枚举 本文 https medium com it works locally persisting swift enumerations with realm
  • 如何解决 CoreData mogenerator 未找到问题

    我收到如下所示的错误 我不知道我错过了什么 我该如何解决这个问题 如下图所示 Users nischalhada Documents XcodePro mnepalnews revisited 2 0 CoreData mogenerato
  • 如何将字符串日期转换为 NSDate?

    我想转换字符串 2014 07 15 06 55 14 198000 00 00 to an NSDate在斯威夫特 尝试这个 let dateFormatter NSDateFormatter dateFormatter dateForm
  • 错误域=AVFoundationErrorDomain代码=-11814“无法记录”

    它不断给我错误 错误域 AVFoundationErrorDomain代码 11814 无法记录 我不确定问题是什么 我试图在拍照后计数器达到 1 时录制声音 static int counter counter will always b
  • 推入 UINavigationController 时隐藏 FBFriendPickerViewController 导航栏

    介绍一个实例FBFriendPickerViewController using presentViewController animated completion 非常简单 该类似乎是针对该用例的 但是 我想推送一个实例FBFriendP
  • iOS 中的构建对象文件扩展名是什么?

    当我在项目中构建java对象类时 将创建带有 class扩展名的构建文件 并且人类不可读 快速构建文件怎么样 example car java gt build gt car class 构建后会是什么 car swift gt build
  • 我的游戏中应该有多少个视图控制器?

    我开始使用 spritekit 构建我的第一个游戏 现在我只有一个视图控制器来呈现开始屏幕场景 override func viewDidLoad super viewDidLoad let scene StartScreenScene C
  • 苹果企业程序分发问题[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 这个问题涉及到Apple iOS 开发者企业计划 http developer apple com programs ios enterprise 我
  • 避免 UIImage 的 imageNamed - 内存管理

    我正在经历这个链接 http akosma com 2009 01 28 10 iphone memory management tips 我遇到了一个点避免 UIImage 的 imageNamed 出于什么原因我们应该避免这种情况 它会
  • Swift C 回调 - Swift 类指针的 takeUnretainedValue 或 takeRetainedValue

    我有一些UIView or UITableViewCell 里面我有 C 回调 例如 CCallback bridge self observer data gt Void in let mySelf Unmanaged
  • Swift 中的 UIAlert 自动消失?

    我有以下代码 Creates Alerts on screen for user func notifyUser title String message String gt Void let alert UIAlertController
  • IPV6 快速可达性

    我是 swift 和 xcode 的新手 并且我的应用程序因 IPV6 而被拒绝 性能 2 1 当我们执行以下操作时 您的应用程序会在运行 iOS 9 3 5 并连接到 IPv6 网络的 iPad 和 iPhone 上崩溃 具体来说 当我们

随机推荐