AVFoundation自定义录像机音频问题

时间:2017-05-19 18:41:17

标签: ios objective-c audio avfoundation

我尝试学习如何创建自定义录像机,除非音频有很多噪音,否则一切正常。我试用系统相机,Instagram或任何其他相机应用程序,他们的音质非常好,并没有某种低级别的声音。此外,与其他相机应用相比,录制的视频音量也明显降低。我无法在stackoverflow上找到任何答案,其中大多数人都回答AVAudioSession而不是AVCaptureSession

以下是我如何实现录像机的代码

_session =  [[AVCaptureSession alloc]init];

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:[devices objectAtIndex:0] error:nil];
if ([_session canAddInput:audioInput])
    [_session addInput:audioInput];

AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
if ( [_session canAddInput:deviceInput] )
    [_session addInput:deviceInput];

_videoOutput = [[AVCaptureVideoDataOutput alloc] init];
_videoOutput.alwaysDiscardsLateVideoFrames = NO;

if ( [_session canAddOutput:_videoOutput] )
    [_session addOutput:_videoOutput];

_audioOutput = [[AVCaptureAudioDataOutput alloc] init];

if ( [_session canAddOutput:_audioOutput] )
    [_session addOutput:_audioOutput];

AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

CALayer *rootLayer = [[self view] layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:CGRectMake(0, 0, rootLayer.bounds.size.width, rootLayer.bounds.size.height)];
[rootLayer insertSublayer:previewLayer atIndex:0];

[_session setSessionPreset:AVCaptureSessionPresetHigh];

dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[_videoOutput setSampleBufferDelegate:self queue:queue];
[_audioOutput setSampleBufferDelegate:self queue:queue];


AVCaptureConnection *videoConnection = [_videoOutput connectionWithMediaType:AVMediaTypeVideo];
[videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];

[_session startRunning];

视频质量很好,代码正常工作,只是在音频部分出现问题。所以

  1. 录制视频时如何改善音频质量?
  2. 如何增加视频的录制音量?
  3. 我知道如何在使用下面的代码纯录制音频时增加它,而不是录制视频时。

     [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:(AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetooth) error:&sessionCategoryError];
    

1 个答案:

答案 0 :(得分:0)

好的,我终于搞清楚了。创建AVCaptureSession后,请执行以下代码。

 AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:(AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetooth) error:nil];
[audioSession setActive:YES error:nil];

_session =  [[AVCaptureSession alloc]init];

//the 2 line below is very important. 
_session.usesApplicationAudioSession = YES;
_session.automaticallyConfiguresApplicationAudioSession = NO;

现在视频的输出音频甚至比系统更好