Recording audio is a complex process – for any computer. iOS makes it simple-ish with several classes courtesy of the AV Foundation Framework.
In this example we’ll record audio from the device microphone. This happens in four steps:
- create an AVSession
- setup a dictionary with audio recorder settings
- create an AVAudioRecorder
- prepare for and start recording
For the method below to work you need to import and link the AVFoundation Framework to your project. We also need a property to hold our AVRecorder object, otherwise it will no longer exist by the time the method reaches the end and nothing will work. Again.
Here’s a method that is called by a “Record Button”:
[emember_protected]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
- (IBAction)recordButtonPressed:(id)sender { // create a URL to an audio asset NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; documentsURL = [documentsURL URLByAppendingPathComponent:@"audiofile.wav"]; // create an audio session AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; // settings for our recorder NSDictionary *audioSettings = @{AVFormatIDKey: [NSNumber numberWithInt:kAudioFormatLinearPCM], AVSampleRateKey: [NSNumber numberWithFloat:22050], AVNumberOfChannelsKey: [NSNumber numberWithInt:1] }; // create an audio recorder with the above settings and URL self.recorder = [[AVAudioRecorder alloc]initWithURL:documentsURL settings:audioSettings error:nil]; self.recorder.delegate = self; [self.recorder prepareToRecord]; [self.recorder record]; } |
You can customise your recorder with various settings as explained in the Apple documentation. And when you’re finished, simply stop the recorder:
1 |
[self.recorder stop]; |
We can also implement an optional delegate method to check if and when recording has finished or if things went wrong:
1 2 3 4 5 6 7 8 9 |
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag { // we're done recording } - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error { // uh-oh... something went wrong } |
[/emember_protected]
Additional delegate methods are available to check for a “higher power” interruption, such as a phone call.
- https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html
- https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVFoundationAudioSettings_Constants/Reference/reference.html#//apple_ref/doc/uid/TP40009937
- http://pinkstone.co.uk/how-to-play-audio-in-ios/