2

So the quesion is simple: how to capture WAV file using AVCaptureDevice, AVCaptureSession, AVCaptureDeviceInput and AVCaptureAudioFileOutput with specific sampling frequency, bitrate etc.? I have the code:

captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
NSError *error = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error];
AVCaptureAudioFileOutput *audioOutput = [[AVCaptureAudioFileOutput alloc] init];
if (audioInput && [captureSession canAddInput:audioInput] && [captureSession canAddOutput:audioOutput]) {
        [captureSession addInput:audioInput];
        [captureSession addOutput:audioOutput];
        [captureSession startRunning];
    }

After that, I handle starting in other function:

- (void)captureSessionStartedNotification:(NSNotification *)notification
{
    AVCaptureSession *session = notification.object;
    id audioOutput  = session.outputs[0];
    .......
    [audioOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:filePath] outputFileType:AVFileTypeWAVE recordingDelegate:self];
}

Where can I set properies of capturing or stuff like this? P.S. setSessionPreset isn't working at all.

Anton Kasabutski
  • 355
  • 5
  • 16
  • Check out http://stackoverflow.com/questions/11631996/how-to-set-audio-sample-rate-on-avcapturesession – jtbandes May 18 '16 at 02:17
  • @jtbandes Already saw that post. They are talk about iOS. I am talking about osx. I saw another post http://stackoverflow.com/questions/15336434/how-to-change-audio-recording-settings-to-16khz-and-16-bit-when-we-record-audio, it helped a bit, I can change frequency, but I still have issue with bitrate of wav file. – Anton Kasabutski May 18 '16 at 02:32

1 Answers1

3

Okay, so its not totally that I've expected, but anyway I've come up with solution. In my case, I needed AVSampleRateKey eq to 16000, AVLinearPCMBitDepthKey eq to 16 and 1 channel. But unfortunately, to set those properties and try to record wav format kind of complicated. To set properties I used:

NSDictionary *recordSettings = [NSDictionary
                                    dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithInt:kAudioFormatLinearPCM],
                                    AVFormatIDKey,
                                    [NSNumber numberWithInt:16],
                                    AVLinearPCMBitDepthKey,
                                    [NSNumber numberWithBool:NO],
                                    AVLinearPCMIsFloatKey,
                                    [NSNumber numberWithInt: 1],
                                    AVNumberOfChannelsKey,
                                    [NSNumber numberWithFloat:16000.0],
                                    AVSampleRateKey,
                                    nil];

    [audioOutput setAudioSettings:recordSettings];

And there is two options:

  1. [audioOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:filePath] outputFileType:AVFileTypeCoreAudioFormat recordingDelegate:self];
  2. [audioOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:filePath] outputFileType:AVFileTypeWAVE recordingDelegate:self];

In first case I could write even .wav file, but for some reasons some of properties, that I've set above, didn't work at all (for example, frequency). In second case I couldn't even write anything. All lines went w/o errors, but in some point, file didn't get created. So the decision was made: write .caf with my params and then convert it to desired .wav file. So settings above + 1st case can write simple .caf file. After that I used convertion function:

-(BOOL)convertFromCafToWav:(NSString*)filePath
{
    NSError *error = nil ;

    NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [ NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                                  [ NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                                  [ NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                                  [ NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
                                  [ NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,
                                  [ NSNumber numberWithBool:0], AVLinearPCMIsBigEndianKey,
                                  [ NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
                                  [ NSData data], AVChannelLayoutKey, nil ];

    NSString *audioFilePath = filePath;
    AVURLAsset * URLAsset = [[AVURLAsset alloc]  initWithURL:[NSURL fileURLWithPath:audioFilePath] options:nil];

    if (!URLAsset) return NO ;

    AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:URLAsset error:&error];
    if (error) return NO;

    NSArray *tracks = [URLAsset tracksWithMediaType:AVMediaTypeAudio];
    if (![tracks count]) return NO;

    AVAssetReaderAudioMixOutput *audioMixOutput = [AVAssetReaderAudioMixOutput
                                                   assetReaderAudioMixOutputWithAudioTracks:tracks
                                                   audioSettings :audioSetting];

    if (![assetReader canAddOutput:audioMixOutput]) return NO ;

    [assetReader addOutput :audioMixOutput];

    if (![assetReader startReading]) return NO;

    NSString *outPath = [NSString stringWithFormat:@"%@/%@.wav", NSHomeDirectory(), @"myWav"]; //for example

    NSURL *outURL = [NSURL fileURLWithPath:outPath];
    AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:outURL
                                                          fileType:AVFileTypeWAVE
                                                             error:&error];
    if (error) return NO;
    AVAssetWriterInput *assetWriterInput = [ AVAssetWriterInput assetWriterInputWithMediaType :AVMediaTypeAudio
                                                                                outputSettings:audioSetting];
    assetWriterInput. expectsMediaDataInRealTime = NO;
    if (![assetWriter canAddInput:assetWriterInput]) return NO ;
    [assetWriter addInput :assetWriterInput];
    if (![assetWriter startWriting]) return NO;
    [assetWriter startSessionAtSourceTime:kCMTimeZero ];
    dispatch_queue_t queue = dispatch_queue_create( "assetWriterQueue", NULL );
    [assetWriterInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
        while (TRUE)
        {
            if ([assetWriterInput isReadyForMoreMediaData] && (assetReader.status == AVAssetReaderStatusReading)) {

                CMSampleBufferRef sampleBuffer = [audioMixOutput copyNextSampleBuffer];

                if (sampleBuffer) {
                    [assetWriterInput appendSampleBuffer :sampleBuffer];
                    CFRelease(sampleBuffer);
                } else {
                    [assetWriterInput markAsFinished];
                    break;
                }
            }
        }
        [assetWriter finishWritingWithCompletionHandler:^{}];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir;
        NSString* resultDir = NSHomeDirectory(); //for example
        if([fileManager fileExistsAtPath:resultDir isDirectory:&isDir]){
            if ([fileManager fileExistsAtPath:cafPath]){
                [fileManager removeItemAtPath:cafPath error:nil];
            }
        }

    }];
    return YES;
}

Thanks that answer: Passing Sound (wav) file to javascript from objective c

Community
  • 1
  • 1
Anton Kasabutski
  • 355
  • 5
  • 16