AVCaptureSession Запись видео со звуком

У меня есть приложение, настроенное для записи видео с камеры с помощью 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, который находится в фоновом режиме. Есть какие-нибудь мысли о том, что могло бы воспроизводить одно видео и одновременно записывать аудио и видео с камеры?


person user717452    schedule 27.04.2012    source источник
comment
@MDT, так что мне делать? Если вы собираетесь разместить ссылку, почему бы не сделать ее ссылкой на то, что, по вашему мнению, может мне помочь?   -  person user717452    schedule 27.04.2012
comment
См. Добавленный последний абзац для редактирования   -  person user717452    schedule 28.04.2012


Ответы (3)


Вы не включили аудиоустройство:

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

между beginConfiguration и commitConfiguration. Будет работать !!!

person user1249876    schedule 07.06.2012
comment
по какой-то причине, когда я добавляю AudioInput и начинаю запись, предварительный просмотр зависает, а файл вывода видео продолжает сообщать 0 секунд записанного материала ... как только я прокомментирую звук, он снова начинает работать :( - person Moonwalker; 09.07.2013

Добавьте ниже код между 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.")
}
person Abdul Yasin    schedule 23.03.2016
comment
Вопрос касается ObjectiveC, а не Swift - person NSNoob; 15.08.2016

в быстром 5x вы можете использовать это:

do {
        guard let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio) else {
            print("Default audio device is unavailable.")
            setupResult = .configurationFailed
            session.commitConfiguration()
            return
        }

        // Add audio input
        let audioInput = try AVCaptureDeviceInput(device: audioDevice)
        if session.canAddInput(audioInput) {
            session.addInput(audioInput)
        } else {
            print("Couldn't add audio device input to the session.")
            setupResult = .configurationFailed
            session.commitConfiguration()
            return
        }

    } catch {
        print("Couldn't create Audio device input: \(error)")
        setupResult = .configurationFailed
        session.commitConfiguration()
        return
    }
person Mohsen mokhtari    schedule 23.01.2021