Skip to content

IOS:AVAudioRecorder

An instance of the AVAudioRecorder class, called an audio recorder, provides audio recording capability in your application. Using an audio recorder you can:

  • Record until the user stops the recording
  • Record for a specified duration
  • Pause and resume a recording
  • Obtain input audio-level data that you can use to provide level metering

Sample code

AVAudioRecorder를 사용하여 녹음하는 간단한 샘플 프로그램은 아래와 같다.

#import <AVFoundation/AVFoundation.h>
// ...
@property (nonatomic, retain) AVAudioRecorder * recorder;
// ...
@synthesize recorder;
// ...
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self record];
}

- (NSURL*)urlForNewLocalAudiolFile
{
    // return [self urlForNewLocalAudiolFile:@"sample.aud"];
    return [self urlForNewLocalAudiolFile:@"MyAudioMemo.m4a"];
}

- (NSURL*)urlForNewLocalAudiolFile:(NSString*)name
{
//    NSFileManager * fileManager = [NSFileManager defaultManager];
//    NSArray * URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
//    NSURL * url = [URLs objectAtIndex:0];
//    return [url URLByAppendingPathComponent:name];

    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects:
                               [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], name, nil];
    NSURL * outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    return outputFileURL;
}

- (void)record
{
    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    recordUrl = [self urlForNewLocalAudiolFile];

    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:NULL];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];
}

- (IBAction)onTouchStartRecord:(id)sender
{
    [self record];
    if (recorder.recording == YES) {
        [recorder pause];
    } else {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [recorder record];
    }
}

Download

  • AVAudioPlayer-AVAudioRecorder-Demo-by.lcw.zip
  • VoIP-RecorderTest-by.jdk.zip

Favorite site

References


  1. Iosappdev_-_AudioRecordingSample.zip