Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioRecorder records blank file

The following are the contents of my record button method. It creates the desired file, but no matter how long I record, the created file is always 4kb and 0 seconds in length and I cannot figure out why it is invalid. The metering is also returning -120 for averagePowerPerChannel and I'm assuming its because the file is corrupt.

NSDictionary *recordSettings = [NSDictionary
                                    dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithInt:AVAudioQualityMin],
                                    AVEncoderAudioQualityKey,
                                    [NSNumber numberWithInt:16],
                                    AVEncoderBitRateKey,
                                    [NSNumber numberWithInt: 2],
                                    AVNumberOfChannelsKey,
                                    [NSNumber numberWithFloat:44100.0], 
                                    AVSampleRateKey,
                                    nil];
    NSError *error;
    NSArray *dirPaths;
    NSString *docsDir;

    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    NSString *soundFilePath = [docsDir
                               stringByAppendingPathComponent:@"sound.caf"];

    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    self.shotRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error];
    self.shotRecorder.delegate = self;

    if (error)
    {
        NSLog(@"error: %@", [error localizedDescription]);

    } else {
        [self.shotRecorder prepareToRecord];
        self.shotRecorder.meteringEnabled = YES;
        [self.shotRecorder record];
        shotTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
    }
like image 935
Matt Avatar asked Oct 02 '13 16:10

Matt


2 Answers

Before you begin the recording, set the AudioSession for your app to one of the session types that supports recording. For example, call this before beginning the recording:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];

If you attempt to do a recording with the AudioSession set to a type that doesn't support recording, the code appears to execute fine, but will result in the empty 4kb audio files you described.

To play the file later, be sure to set the category back to one that supports playback, for example, AVAudioSessionCategoryPlayback, or AVAudioSessionCategoryPlayAndRecord.

like image 163
karstkhan Avatar answered Oct 31 '22 13:10

karstkhan


AVRecorder also records an empty file when app hasn't microphone permission.

like image 31
Igor Avatar answered Oct 31 '22 13:10

Igor