AVAudioRecorder is also built on top of Audio Queue Services. It provides capability to:
Record until user stop the recording
Record for a specified duration
Pause and resume recording
Audio-level metering
For recording and playback, we should choose AVAudioSessionCategoryPlayAndRecord for AVAudioSession category. In order to use the microphone on our device, we need add microphone usage key to application.plist file.
1 2
<key>NSMicrophoneUsageDescription</key> <string>Need to use the microphone to record</string>
Create AVAudioRecorder
To create an AVAudioRecorder, we need a url to specify a location to record to, a dictionary of settings for the recording session and output error.
We can configure several different things for our recording session. The general settings are audio data format, sampling rate and number of channels.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
NSMutableDictionary *setting = [NSMutableDictionary dictionary]; /* set format ** Note: the audio format we specify must be compatible with the tpye defined in the url argument. For example, ** .wav pairs to kAudioFormatLinearPCM ** .aac .m4a pair to kAudioFormatMPEG4AAC ** .alac pairs to kAudioFormatAppleLossless */ [setting setValue:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey]; /* set sampling rate ** Standard sampling rate for audio: 8kHz, 16kHz, 22.05kHz, 44.1kHz */ [setting setValue:@(16000.0) forKey:AVSampleRateKey]; /* set channal ** 1 is for single channel, 2 is for stereo */ [setting setValue:@(1) forKey:AVNumberOfChannelsKey];
AVAudioRecorder needs a place to store the recording audio file. It is a good practice that store the audio file in the temporary directory in iOS file system during recording, and then copy the file to documents directory for permanent saving.
/* When saving the audio */ // create destination url for audio file // use timestamp to be the unique id NSTimeInterval timestamp = [NSDate timeIntervalSinceRefernceDate]; NSString *fileName = [NSString stringWithFormat:@"%@-%f.caf", audioName, timestamp];
// use NSFileManager to copy the file NSError *error; if (![[NSFileManager defaultManager] copyItemAtURL:tmpURL toURL:destURL error:&error]){ NSLog(@"%@", [error localizedDescription]); }