Search code examples
iphonevoiceaudiovoice-recording

Best API for instant voice playback on iPhone?


What I am trying to do:

  • iPhone keep monitoring the voice input channel
  • once the user speaks (recording sound volume > certain level)
  • iPhone starts recording
  • once the use stop speaking (recording volume silence for one second)
  • iPhone plays back the recording

Which iPhone API or sample code should I look into? Thanks!


Solution

  • What you need is AVFoundation. To use it:

    1. Adding AVFoundation.framework to your project
    2. conform your view controller to AVAudioRecorderDelegate, AVAudioPlayerDelegate, one for recording, another one for playing

    Following piece of code is for recording:

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    [audioSession setActive:YES error:&err];
    NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
    [settings setValue: [NSNumber numberWithInt:kAudioFormatMPEGLayer3] forKey:AVFormatIDKey];
    [settings setValue: [NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
    [settings setValue: [NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    NSURL *url = [NSURL fileURLWithPath: filepath];
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:settings error:&err];
    [settings release];
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    [recorder record];
    

    Addtionally, you need to implement - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) recorder successfully:(BOOL)flag to release the recorder.

    Please see more details here: http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40010188