我使用下面的代码来设置一个 AVCaptureSession,录制一个视频文件并播放它: 有时这工作得很好,而其他时候我在播放时会出现黑屏。据我所知,这完全是随机的。
当错误发生时,如果我尝试快速打开文件,我会收到“文件无法打开,格式无法识别”的消息。这让我相信这是一个录制问题而不是播放问题。
此外,如果注释掉添加麦克风输入的代码部分,则不会发生错误(但我的视频文件当然没有音轨)......所以音频馈送可能会随机损坏文件原因?
- (void)viewDidLoad {
[super viewDidLoad];
....
captureSession = [[AVCaptureSession alloc] init];
[captureSession setSessionPreset:AVCaptureSessionPresetHigh];
NSArray *devices = [AVCaptureDevice devices];
AVCaptureDevice *frontCamera;
AVCaptureDevice *mic = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
for (AVCaptureDevice *device in devices) {
NSLog(@"Device name: %@", [device localizedName]);
if ([device hasMediaType:AVMediaTypeVideo])
{
if ([device position] == AVCaptureDevicePositionFront) {
NSLog(@"Device position : front");
frontCamera = device;
}
}
}
NSError *error = nil;
AVCaptureDeviceInput * microphone_input = [AVCaptureDeviceInput deviceInputWithDevice:mic error:&error];
AVCaptureDeviceInput *frontFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
if (!error)
{
if ([captureSession canAddInput:frontFacingCameraDeviceInput])
{
[captureSession addInput:frontFacingCameraDeviceInput];
}
if([captureSession canAddInput:microphone_input])
{
[captureSession addInput:microphone_input];
}
}
[captureSession startRunning];
}
当按下录制时,我录制到一个“movie.mov”文件:
movieOutput = [[AVCaptureMovieFileOutput alloc]init];
[captureSession addOutput:movieOutput];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathString = [documentsDirectory stringByAppendingPathComponent:@"movie.mov"];
NSURL *pathUrl = [NSURL fileURLWithPath:pathString];
[movieOutput startRecordingToOutputFileURL:pathUrl recordingDelegate:self];
当按下播放时,我播放电影文件:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathString = [documentsDirectory stringByAppendingPathComponent:@"movie.mov"];
NSURL *pathUrl = [NSURL fileURLWithPath:pathString];
mPlayer = [AVPlayer playerWithURL:pathUrl];
[self.video setPlayer:self.mPlayer];
[video setVideoFillMode:@"AVLayerVideoGravityResizeAspectFill"];
[self.mPlayer play];
我已经有一段时间了,现在无法弄清楚,这真的很随机。任何帮助表示赞赏!
编辑:如果 movie.mov 文件已经存在,我会在开始新录制之前将其删除。
EDIT2:它是否与该行有关:
[movieOutput startRecordingToOutputFileURL:pathUrl recordingDelegate:self];
Xcode 在此行上给我一个“发送 ViewController *const_strong 'to parameter of in compatible type 'id'”警告
EDIT3:问题已解决,将很快发布答案。谢谢!