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];
}
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.
AVRecorder also records an empty file when app hasn't microphone permission.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With