1、导入头文件
#import <AVFoundation/AVFoundation.h>
2、声明 路径和录音对象
@property(nonatomic,strong) NSURL * url;
@property(nonatomic,strong) AVAudioRecorder* recorder;
-(NSURL *)url{
if (_url == nil) {
NSString *tmpDir = NSTemporaryDirectory();
NSString *urlPath = [tmpDir stringByAppendingString:@"record.caf"];
_url = [NSURL fileURLWithPath:urlPath];
}
NSLog(@"url");
return _url;
}
-(void)startRcd{
NSError *error = nil;
//激活AVAudioSession
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (session != nil) {
[session setActive:YES error:nil];
}else {
NSLog(@"session error: %@",error);
}
//设置AVAudioRecorder类的setting参数
NSDictionary *recorderSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat:16000.0],AVSampleRateKey,
[NSNumber numberWithInt:kAudioFormatAppleIMA4],AVFormatIDKey,
[NSNumber numberWithInt:1],AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
//实例化AVAudioRecorder对象
self.recorder = [[AVAudioRecorder alloc] initWithURL:self.url settings:recorderSettings error:&error];
if (error) {
NSLog(@"recorder error: %@", error);
}
//准备录音
[self.recorder prepareToRecord];
//开始录音
[self.recorder record];
NSLog(@"start");
}
//结束录音
-(void)stopRcd{
[self.recorder stop];
//释放self.recorder,否则无法更新录音文件,即不能进行二次录音
self.recorder = nil;
NSLog(@"end");
}