标签:
1.导入头文件,声明属性
#import <MobileCoreServices/MobileCoreServices.h> @property (nonatomic,strong) AVAudioPlayer * audioPlayerSend; @property (nonatomic,strong) AVAudioSession * audioSession; @property (nonatomic,strong) AVAudioRecorder * audioRecorder;
2.定制录音按钮
self.longPressRecordBtn=[UIButton buttonWithType:UIButtonTypeCustom]; self.longPressRecordBtn.frame=CGRectMake(50, 7, _screenW-140, 30); [self.longPressRecordBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.longPressRecordBtn setTitle:[NSString stringWithFormat:@"按住 说话"] forState:UIControlStateNormal]; [self.longPressRecordBtn setTitle:[NSString stringWithFormat:@"松开 结束"] forState:UIControlStateHighlighted]; [self.longPressRecordBtn setBackgroundImage:[UIImage imageNamed:@"bg_Tool_Record"] forState:UIControlStateNormal]; [self.longPressRecordBtn addTarget:self action:@selector(talkPrepare) forControlEvents:UIControlEventTouchDown]; [self.longPressRecordBtn addTarget:self action:@selector(talkSend) forControlEvents:UIControlEventTouchUpInside]; [self.longPressRecordBtn addTarget:self action:@selector(recordViewBtnCancel) forControlEvents:UIControlEventTouchDragOutside]; [self.longPressRecordBtn addTarget:self action:@selector(recordViewBtnRecording) forControlEvents:UIControlEventTouchDragInside]; [self.longPressRecordBtn addTarget:self action:@selector(talkCancel) forControlEvents:UIControlEventTouchUpOutside]; self.longPressRecordBtn.hidden=YES;
3.开始录音方法
-(void)startAudioRecord { [_audioSession setActive:YES error: nil]; // NSString * nnPKChat = [Util GetUUID]; // NSString * nPKChat = [nnPKChat lowercaseString]; // 获取音频文件的保存路径 NSString *destinationString = [SaveAudioVoiceDataEngine getRecordTemporaryVoiceWholePath]; NSURL *destinationURL = [NSURL fileURLWithPath:destinationString]; // 创建一个NSDictionary,用于保存录制属性 NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init]; // 设置录制音频的格式 [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey]; // 设置录制音频的采样率 // float sampleRate=11025.0; float sampleRate=8000.0; [recordSettings setObject:[NSNumber numberWithFloat: sampleRate] forKey: AVSampleRateKey]; // 设置录制音频的通道数 NSInteger ch=1; [recordSettings setObject: [NSNumber numberWithInt:ch] forKey:AVNumberOfChannelsKey]; // 设置录制音频的每个样点的位数 NSInteger bi=16; [recordSettings setObject: [NSNumber numberWithInt:bi] forKey:AVLinearPCMBitDepthKey]; // // 设置录制音频采用高位优先的记录格式 // [recordSettings setObject:[NSNumber numberWithBool:NO] // forKey:AVLinearPCMIsBigEndianKey]; // // // 设置采样信号采用浮点数 // [recordSettings setObject:[NSNumber numberWithBool:NO] // forKey:AVLinearPCMIsFloatKey]; // // // 音频质量 // [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey]; NSError *recorderSetupError = nil; // 初始化AVAudioRecorder self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationURL settings:recordSettings error:&recorderSetupError]; self.audioRecorder.meteringEnabled=YES; [self.audioRecorder updateMeters]; self.audioRecorder.delegate = self; [self.audioRecorder record]; _recordTimeNum=0.0; _recordingTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(volumeChange) userInfo:nil repeats:YES]; }
4.说话声音大小改变图片(并且存储临时声音文件)
-(void)volumeChange { _recordTimeNum+=0.5; if (self.audioRecorder) { if (_recordTimeNum < 50) { [self.audioRecorder updateMeters]; float h = pow(10, (0.05 * [self.audioRecorder peakPowerForChannel:0])); NSInteger vh = ceilf(h * 8); NSLog(@"---%f",h); self.recordingHUD.showVolumeView.image=[UIImage imageNamed:[NSString stringWithFormat:@"icon_chat_microphone%d",vh]]; }else if (_recordTimeNum < 60) { [self showCancelRecordHUD]; _cancelRecordHUD.statusLab.text=[NSString stringWithFormat:@"%.0f",ceilf(_recordTimeNum)]; }else if (_recordTimeNum == 60) { _timeoutSended=YES; [self hidenRecordHUD]; [self recordEndToSend]; } } }
5.发送语音消息
-(void)recordEndToSend { [self closeAudioSessionAndAudioRecord]; NSString *destinationString = [SaveAudioVoiceDataEngine getRecordTemporaryVoiceWholePath]; NSURL *destinationURL = [NSURL fileURLWithPath:destinationString]; AVAudioPlayer * avap = [[AVAudioPlayer alloc]initWithContentsOfURL:destinationURL error:nil]; NSInteger l=(int)avap.duration; if (l >= 1) { NSString * nnPKChat = [Util GetUUID]; NSString * nPKChat = [nnPKChat lowercaseString]; NSString * updatePath = [SaveAudioVoiceDataEngine spliceRelativePathWithWithPKVoice:nPKChat phoneNumber:self.friendPhoneNumber pathType:1]; [VoiceConverter wavToAmr:[SaveAudioVoiceDataEngine getRecordTemporaryVoiceWholePath] amrSavePath:[SaveAudioVoiceDataEngine getVoiceLocalWholePathWithPath:updatePath PKVoice:nPKChat]]; MessageObj * obj = [[MessageObj alloc]init]; obj.PKChat=nPKChat; obj.MessageType = 4; obj.MessageFromType=1; obj.PKUserFrom = _myUserStr; obj.MessageActions=@""; obj.createTime = [Util getNowDateTime]; obj.voiceLength = l; obj.voiceStatus=1; obj.VoiceRelPath=updatePath; obj.messageSize = CGSizeMake(20, 20); [_array addObject:obj]; [self.chatTableView reloadData]; if (_array.count>0) { [self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_array.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; } _recordTimeNum=0; [SNSInfomationEngine operateChatInfomationToSQLWithMessageObj:obj PKUserTo:self.PKUserFriend imageSize:CGSizeZero]; [SaveAudioVoiceDataEngine sendChatVoiceWithMessageObj:obj PKUserTo:self.PKUserFriend chatMsgServer:self.chatMsgSer UserHostServer:_appdelegate.serviceUrl phoneNumber:self.friendPhoneNumber success:^ { NSLog(@"sendVoiceSuccess"); } Failure:^ { NSLog(@"sendVoicefailure"); }]; }else { NSLog(@"说话时间太短"); } }
标签:
原文地址:http://www.cnblogs.com/liaods/p/4887151.html