-->

AVCaptureSession录制有声短片(AVCaptureSession Record Vid

2019-07-29 04:00发布

我有我的应用程序设置为记录使用AVCaptureSession摄像头的视频,然而,有一个与它没有音讯。 我需要做什么做的录制音频,然后将其添加到videoOutput的文件? 这里是我的录制视频的代码:

AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
session.sessionPreset = AVCaptureSessionPresetMedium;

CALayer *viewLayer = self.vImagePreview.layer;
NSLog(@"viewLayer = %@", viewLayer);

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.frame = self.vImagePreview.bounds;

[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

AVCaptureDevice *device = [self frontFacingCameraIfAvailable];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    NSLog(@"ERROR: trying to open camera: %@", error);
}

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];

AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

NSString *archives = [documentsDirectoryPath stringByAppendingPathComponent:@"archives"];
NSString *outputpathofmovie = [[archives stringByAppendingPathComponent:@"Test"] stringByAppendingString:@".mp4"];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];

[session addInput:input];
[session addOutput:movieFileOutput];
[session commitConfiguration];
[session startRunning];
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

我又增加了输入音频,但它不会与在背景中的MPMoviePlayerController工作。 是否有任何想法的东西,可以发挥一个视频,并同时记录从摄像头的音频和视频?

Answer 1:

您还没有包括音频设备:

AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
[session addInput:audioInput]

之间beginConfigurationcommitConfiguration 。 它会工作!



Answer 2:

下面添加代码之间beginConfiguration()commitConfiguration()

// Add audio device to the recording

let audioDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
do {
    let audioInput = try AVCaptureDeviceInput(device: audioDevice)
    self.captureSession.addInput(audioInput)
} catch {
    print("Unable to add audio device to the recording.")
}


文章来源: AVCaptureSession Record Video With Audio