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.

10 Replies to “How To: iPhone SDK – Play and Record Audio concurrently”

  1. Hi.
    Thanks lot for for this post. The last 3 lines of code were really useful.

    I also wanted to know if there is a way to record what you are playing without using the mic input.
    For example if I am listing to a radio stream, is it possible to record the audio?

    Thnaks again for the post

    Ed

  2. /dev/null PROBLEM!

    If you analize the app in Instruments (with IO and Memory module) then you can see that memory just keeps growing. (dev/NULL write operations)

    For example: if you are metering audio leveles every 1 second.

    How can I solve this?

  3. Ed:

    Apple doesnt wants you to record any audio due to copy rights, but TuneIn Radio app has such feature. So, dunno the real thing.

  4. I have tried to use this but failed. What i am actually trying to do is to playback the same what is being recorded simultaneously. No output is got at the speaker. I have tried with all the remaining SDKs but no result

  5. Can you provide the complete source code for recording and playing at the same time ….as you have only provided some sinppets of code am getting confused where to write the above mentioned code in my application.

Leave a Reply