Skip to content

Instantly share code, notes, and snippets.

Created August 22, 2011 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1162105 to your computer and use it in GitHub Desktop.
Save anonymous/1162105 to your computer and use it in GitHub Desktop.
record sound
// set the audio session's category to record
[[AVAudioSession sharedInstance] setCategory:
AVAudioSessionCategoryRecord error:nil];
// find the location of the document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
// get the first directory
NSString *dir = [paths objectAtIndex:0];
// create a name for the file using the current system time
NSString *filename = [NSString stringWithFormat:@"%f.caf",
[[NSDate date] timeIntervalSince1970]];
// create the path using the directory and file name
NSString *path = [dir stringByAppendingPathComponent:filename];
// create a new NSMutableDictionary for the record settings
NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
// record using the Apple lossless format
[settings setValue: [NSNumber
numberWithInt:kAudioFormatAppleLossless] forKey:AVFormatIDKey];
// set the sample rate to 44100 Hz
[settings setValue:[NSNumber
numberWithFloat:44100.0] forKey:AVSampleRateKey];
// set the number of channels for recording
[settings setValue:[NSNumber numberWithInt:1]
forKey:AVNumberOfChannelsKey];
// set the bit depth
[settings setValue:[NSNumber numberWithInt:16]
forKey:AVLinearPCMBitDepthKey];
// set whether the format is big endian
[settings setValue:[NSNumber numberWithBool:NO]
forKey:AVLinearPCMIsBigEndianKey];
// set whether the audio format is floating point
[settings setValue:[NSNumber numberWithBool:NO]
forKey:AVLinearPCMIsFloatKey];
[visualizer clear]; // clear the visualizer
[recorder release]; // release the recorder AVAudioRecorder
// initialize recorder with the URL and settings
recorder =
[[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:path]
settings:settings error:nil];
[recorder prepareToRecord]; // prepare the recorder to record
recorder.meteringEnabled = YES; // enable metering for the recorder
[recorder record]; // start the recording
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment