
IM即时通讯
安全可靠、全球互通

实时音视频
流畅稳定、省钱省力
回答:
1、设置语音录制参数
NSDictionary *recordSettings = @{ AVFormatIDKey : @(kAudioFormatMPEG4AAC_HE), AVNumberOfChannelsKey : @1, AVEncoderBitRateKey : @(32000) };
2、生成临时语音存放路径
NSURL *recordTempFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"HQTempAC.m4a"]];
3、录制高清语音消息
AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryRecord error:nil]; [audioSession setActive:YES error:nil]; NSError *error = nil; if (nil == self.recorder) { AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:recordTempFileURL settings:recordSettings error:&error]; recorder.delegate = self; recorder.meteringEnabled = YES; } // 准备录音 [recorder prepareToRecord]; // 开始录音 [recorder record];
4、 录制完成后发布语音消息
if (!recorder.url){ return;} NSURL *url = [[NSURL alloc] initWithString:recorder.url.absoluteString]; // 当前录音时长 NSTimeInterval audioLength = recorder.currentTime; // 停止录音 [recorder stop]; // 录音文件 data NSData *currentRecordData = [NSData dataWithContentsOfURL:url]; recorder = nil; // 将语音从临时路径放到永久路径。 NSString *path = [self getHQVoiceMessageCachePath]; [currentRecordData writeToFile:path atomically:YES]; // 构造高清语音消息 RCHQVoiceMessage *hqVoiceMsg = [RCHQVoiceMessage messageWithPath:path duration:audioLength]; // 发送消息 RCMessage *message = [[RCMessage alloc] initWithType:ConversationType_PRIVATE targetId:@"2" direction:MessageDirection_SEND content:hqVoiceMsg]; [[RCIMClient sharedRCIMClient] sendMediaMessage:message pushContent:nil pushData:nil progress:^(int progress, RCMessage *progressMessage){} successBlock:^(RCMessage *successMessage) { NSLog(@"--- 发送消息成功"); } errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) { NSLog(@"--- 发送消息失败 %ld", nErrorCode); } cancel:^(RCMessage *cancelMessage) {}]; // 语音消息本地路径 - (NSString *)getHQVoiceMessageCachePath { long long currentTime = [[NSDate date] timeIntervalSince1970] * 1000; //路径 NSString *path = [RCUtilities rongImageCacheDirectory]; path = [path stringByAppendingFormat:@"/%@/RCHQVoiceCache", [RCIMClient sharedRCIMClient].currentUserInfo.userId]; if ([[NSFileManager defaultManager] fileExistsAtPath:path] == NO) { [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; } NSString *fileName = [NSString stringWithFormat:@"/Voice_%@.m4a", @(currentTime)]; path = [path stringByAppendingPathComponent:fileName]; NSLog(@"--- path %@", path); return path; }