Thursday, August 18, 2011

Record audio data in a file on iPhone

// setting format of audio data (to be recorded) in a dictionary data structure
NSMutableDictionary *recordSetting = [[ NSMutableDictionary alloc ] init];
[ recordSetting setValue: [ NSNumber numberWithInt: kAudioFormatLinearPCM ] forKey: AVFormatIDKey ];
[ recordSetting setValue: [ NSNumber numberWithFloat: 44100.0 ] forKey: AVSampleRateKey ];
[ recordSetting setValue: [ NSNumber numberWithInt: 1 ] forKey: AVNumberOfChannelsKey ];
[ recordSetting setValue: [ NSNumber numberWithInt: 16 ] forKey: AVLinearPCMBitDepthKey ];
[ recordSetting setValue: [ NSNumber numberWithBool:NO ] forKey: AVLinearPCMIsBigEndianKey ];
[ recordSetting setValue: [ NSNumber numberWithBool:NO ] forKey: AVLinearPCMIsFloatKey ];
// The format is Linear PCM (Pulse Code Modulation), with 44.1 KHz sampling rate, one channel,
// and bit-depth of 16 bits.
// So, each sample is 2 bytes long, because one sample from each channel constitutes one frame;
// here there is only one channel, so a frame is just a sample; last line ensures that audio data
// will not be in floats
// I shall save the data in a file in the Documents directory. So, I need the path to the
// Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
// record the data in a ".caf" (Core Audio File) file
NSURL* recordedTmpFile = [ NSURL fileURLWithPath: [ documentsDirectory stringByAppendingPathComponent: [ NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate]*1000.0, @"caf" ] ] ];
recorder = [ [ AVAudioRecorder alloc ] initWithURL: recordedTmpFile settings: recordSetting error: &error ];
[ recorder setDelegate: self ];
[ recorder prepareToRecord ];
[ recorder record ];

No comments:

Post a Comment