我有一个问题需要解决:我有一个带预览层的AVCaptureSession,我还想在用户点击按钮时提供触觉反馈。如果我向我的AVCaptureSession添加audioInput,则无法产生触觉反馈。我尝试在开始录制之前添加audioInput并立即在停止录制后删除它,但修改捕获会话配置(我在串行队列中执行)会导致视频预览出现短暂的中断。而且我仍然不知道Snapchat和Instagram是如何做到这一点的。我猜测他们可能以某种方式配置了AVAudioSession,但我无法弄清楚。
我的捕获会话初始化非常通用,因此我不会粘贴它(值得注意的是,我有captureSession.automaticallyConfiguresApplicationAudioSession = false
行,并且共享的AVAudioSession被修改为AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVideoRecording, options: [.mixWithOthers])
),但我将发布我的切换音频输入的尝试:
func addAudioInput() {
self.sessionQueue.async { [unowned self] in
self.captureSession.beginConfiguration()
let microphone = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
if let audioInput = try? AVCaptureDeviceInput(device: microphone), self.captureSession.canAddInput(audioInput) {
self.captureSession.addInput(audioInput)
}
self.captureSession.commitConfiguration()
}
}
func removeAudioInput() {
self.sessionQueue.async { [unowned self] in
if let audioInput = self.captureSession.inputs.first(where: { ($0 as? AVCaptureDeviceInput)?.device.deviceType == .builtInMicrophone }) as? AVCaptureDeviceInput {
self.captureSession.beginConfiguration()
self.captureSession.removeInput(audioInput)
self.captureSession.commitConfiguration()
}
}
}