首先导入头文件
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
//初始化一个录音控制器
AVAudioRecorder * recorder;
AVAudioSession* audioSession;
int number;
NSString * urlPlay;
//创建一个录音的按钮,按下按钮开始录音,送开手指录音结束并存在临时文件中
//录音按钮的按下点击事件
- (void)startRecorderButton{
[self audio];
//创建录音文件,准备录音
[recorder prepareToRecord];
//开始
[recorder record];
}
//松开手指的事件
- (void)endRecorderButton{
[recorder stop];
}
- (void)audio{
audioSession= [AVAudioSessionsharedInstance];
[audioSessionsetCategory:AVAudioSessionCategoryRecorderror:nil];
[audioSessionsetActive:YESerror:nil];
//录音设置
NSMutableDictionary*recordSetting = [[NSMutableDictionaryalloc]init];
//设置录音格式
[recordSettingsetValue: [NSNumbernumberWithInt:kAudioFormatMPEG4AAC]forKey:AVFormatIDKey];
//设置录音采样率(Hz)如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
[recordSettingsetValue:[NSNumbernumberWithFloat:44100]forKey:AVSampleRateKey];
//录音通道数1或2
[recordSettingsetValue:[NSNumbernumberWithInt:1]forKey:AVNumberOfChannelsKey];
//线性采样位数8、16、24、32
[recordSettingsetValue:[NSNumbernumberWithInt:16]forKey:AVLinearPCMBitDepthKey];
//录音的质量
[recordSettingsetValue:[NSNumbernumberWithInt:AVAudioQualityHigh]forKey:AVEncoderAudioQualityKey];
NSString*strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
urlPlay= [NSURLfileURLWithPath:[NSStringstringWithFormat:@"%@/%d.aac", strUrl,number++]];
NSError*error;
//初始化
recorder= [[AVAudioRecorderalloc]initWithURL:urlPlaysettings:recordSettingerror:&error];
//开启音量检测
recorder.meteringEnabled=YES;
}
网友评论