1、添加录音按钮(一直按着录音,松手之后录音结束,结束播放录音)
UIButton *speakBut = [UIButton buttonWithType:UIButtonTypeCustom];
speakBut.frame = CGRectMake(60, 340, 200, 40);
[speakBut setBackgroundImage:[UIImage imageNamed:@"btn_orange" cache:NO] forState:UIControlStateNormal];
[speakBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[speakBut addTarget:self action:@selector(btnDown:) forControlEvents:UIControlEventTouchDown];
[speakBut addTarget:self action:@selector(pressToSpeak:) forControlEvents:UIControlEventTouchUpInside];
[speakBut setTitle:@"按住说话" forState:UIControlStateNormal];
[speakBut setTitle:@"正在录音" forState:UIControlStateHighlighted];
speakBut.titleLabel.font = [UIFont boldSystemFontOfSize:25];
[mainView addSubview:speakBut];
//录音文件保存路径
NSString *recordUrl = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
recordUrl = [recordUrl stringByAppendingPathComponent:@"sound.aac"];
//录音设置
NSMutableDictionary *recordSetting = [[[NSMutableDictionary alloc]init] autorelease];
//设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
[recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
//录音通道数 1 或 2
[recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
//线性采样位数 8、16、24、32
[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//录音的质量
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
avRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:recordUrl] settings:recordSetting error:nil];
avRecorder.delegate = self;
avSession = [AVAudioSession sharedInstance];
[avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[avSession setActive:YES error:nil];
//按钮按下方法
- (void)btnDown:(id)sender
{
[avRecorder prepareToRecord];
[avRecorder record];
}
//按钮点击方法
- (void)pressToSpeak:(id)sender{
double cTime = avRecorder.currentTime;
//NSLog(@"sss---->%f",cTime);
if (cTime > 2) {//如果录制时间<2 不发送
NSLog(@"发出去");//可以将音频文件发送后台
}else {
//删除记录的文件
[avRecorder deleteRecording];
//删除存储的
}
[avRecorder stop];
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
[avSession setActive:NO error:nil];
NSString *recordUrl = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
recordUrl = [recordUrl stringByAppendingPathComponent:@"sound.aac"];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:recordUrl] error:nil];
[player play];
}