问题描述: 当使用AVAssetWriter同时录制音频和视频时,应用程序崩溃。
解决方法: 可以使用AVCaptureSession来同时录制音频和视频,避免AVAssetWriter无法处理音频和视频的同时写入。
以下是一个示例代码,展示了如何使用AVCaptureSession来同时录制音频和视频:
import AVFoundation
class Recorder {
var captureSession: AVCaptureSession?
var videoOutput: AVCaptureMovieFileOutput?
var audioOutput: AVCaptureAudioDataOutput?
func startRecording() {
captureSession = AVCaptureSession()
guard let captureSession = captureSession else { return }
// 添加音频输入
let audioDevice = AVCaptureDevice.default(for: .audio)
guard let audioInput = try? AVCaptureDeviceInput(device: audioDevice!) else { return }
if captureSession.canAddInput(audioInput) {
captureSession.addInput(audioInput)
}
// 添加视频输入
let videoDevice = AVCaptureDevice.default(for: .video)
guard let videoInput = try? AVCaptureDeviceInput(device: videoDevice!) else { return }
if captureSession.canAddInput(videoInput) {
captureSession.addInput(videoInput)
}
// 添加音频输出
audioOutput = AVCaptureAudioDataOutput()
if captureSession.canAddOutput(audioOutput!) {
captureSession.addOutput(audioOutput!)
}
// 添加视频输出
videoOutput = AVCaptureMovieFileOutput()
if captureSession.canAddOutput(videoOutput!) {
captureSession.addOutput(videoOutput!)
}
// 设置录制方向
let connection = videoOutput?.connection(with: .video)
connection?.videoOrientation = .portrait
// 开始录制
let outputPath = NSTemporaryDirectory() + "output.mov"
let outputURL = URL(fileURLWithPath: outputPath)
videoOutput?.startRecording(to: outputURL, recordingDelegate: self)
captureSession.startRunning()
}
func stopRecording() {
videoOutput?.stopRecording()
captureSession?.stopRunning()
}
}
extension Recorder: AVCaptureFileOutputRecordingDelegate {
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
// 录制开始
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
// 录制结束
}
}
使用上述代码,可以在开始录制时调用startRecording()
方法,在结束录制时调用stopRecording()
方法。同时录制音频和视频,并且避免了AVAssetWriter无法处理同时写入音频和视频的问题。