AVAssetWriter 在 Swift 中录制视频?
AVAssetWriter Recording Video in Swift?
我已成功设置 AVAssetWriter 来录制视频并将其保存到我的相机胶卷中。唯一的问题是录制视频的第一帧是空白的白帧。有什么办法可以解决这个问题吗?到底是怎么回事?
您是否对视频帧进行了任何操作?就我而言,我在编写视频帧之前调整了它们的大小。在这种情况下,首先写入音频帧,然后在几帧之后写入视频帧。因此,前几帧在预览中显示为白色。但在视频播放中几乎看不出来。
解法:
跳过编写音频帧,直到使用 avasssetwriter 编写视频帧
捕获输出的推荐代码
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection!) {
if CMSampleBufferDataIsReady(sampleBuffer) == false
{
// Handle error
return;
}
startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
if videoWriter.status == AVAssetWriterStatus.Unknown {
videoWriter.startWriting()
videoWriter.startSessionAtSourceTime(startTime)
return
}
if videoWriter.status == AVAssetWriterStatus.Failed {
// Handle error here
return;
}
// Here you collect each frame and process it
if(recordingInProgress){
if let _ = captureOutput as? AVCaptureVideoDataOutput {
if videoWriterInput.isReadyForMoreMediaData{
videoWriterInput.append(sampleBuffer)
video_frames_written = true
}
}
if let _ = captureOutput as? AVCaptureAudioDataOutput {
if audioWriterInput.isReadyForMoreMediaData && video_frames_written{
audioWriterInput.append(sampleBuffer)
}
}
}
}
我已成功设置 AVAssetWriter 来录制视频并将其保存到我的相机胶卷中。唯一的问题是录制视频的第一帧是空白的白帧。有什么办法可以解决这个问题吗?到底是怎么回事?
您是否对视频帧进行了任何操作?就我而言,我在编写视频帧之前调整了它们的大小。在这种情况下,首先写入音频帧,然后在几帧之后写入视频帧。因此,前几帧在预览中显示为白色。但在视频播放中几乎看不出来。
解法:
跳过编写音频帧,直到使用 avasssetwriter 编写视频帧
捕获输出的推荐代码
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection!) {
if CMSampleBufferDataIsReady(sampleBuffer) == false
{
// Handle error
return;
}
startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
if videoWriter.status == AVAssetWriterStatus.Unknown {
videoWriter.startWriting()
videoWriter.startSessionAtSourceTime(startTime)
return
}
if videoWriter.status == AVAssetWriterStatus.Failed {
// Handle error here
return;
}
// Here you collect each frame and process it
if(recordingInProgress){
if let _ = captureOutput as? AVCaptureVideoDataOutput {
if videoWriterInput.isReadyForMoreMediaData{
videoWriterInput.append(sampleBuffer)
video_frames_written = true
}
}
if let _ = captureOutput as? AVCaptureAudioDataOutput {
if audioWriterInput.isReadyForMoreMediaData && video_frames_written{
audioWriterInput.append(sampleBuffer)
}
}
}
}