How To: iPhone SDK – Play and Record Audio concurrently
Unfortunately, it’s quite a fiddly process to record audio and play it back at the same time on the iPhone. By default, the sound output is very quiet from the iPhone’s speaker when you are recording sound. So how do we fix this?
First, setup your audio session to record audio:
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil];
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
} else {
NSLog(@"Error: %@", error);
}
Then tell the device you want to record and play audio at the same time:
AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *err = nil; [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
Then, and this is the key, allow the volume from the speakers to also be loud when recording:
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride),&audioRouteOverride);
The end result? You can happily play audio at full volume while recording from the device’s microphone. Happy days.

Leave a Reply