1.拖一个按钮覆盖textView,设置高度和textView一样,左右下的约束和textView一样。默认隐藏。
点击了左边vioceBtn按钮才显示
#pragma mark - action
/**
* VoiceBtn被点击了
*/
- (IBAction)clickedVoiceBtn:(UIButton *)sender
{
// 按钮图片切换
self.voiceBtn.selected = !self.voiceBtn.selected;
// 1.显示录音按钮
self.recordBtn.hidden = !self.recordBtn.hidden;
}
2.录音按钮recordBtn设置几个事件分别处理 “按住录音”,“松开发送”
3.导入2个第三方框架(就在环信的demo里),完成录音功能
command+b编译一下,如果出现xxx未定义,就导入相关头文件
在聊天控制器导入:
#import "EMCDDeviceManager.h"
/**
* 手指按下去开始录音
*/
- (IBAction)touchDownRecordBtn:(id)sender
{
// 文件名以时间命令
int x = arc4random() % 100000;
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
[[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error) {
if (!error) {
//开始录音成功
}
}];
}
/**
* 手指松开结束录音
*/
- (IBAction)touchUpInsideRecordBtn:(id)sender
{
[[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
if (!error) {
//录音完成
//发送语音
[self sendVoice:recordPath duration:aDuration];
}
}];
}
/**
* 发送语音
*
* @param recordPath 语音文件路径
* @param duration 时间
*/
- (void)sendVoice:(NSString *)recordPath duration:(NSInteger)duration
{
// 1.构造一个 语音消息体
EMChatVoice *chatVoice = [[EMChatVoice alloc] initWithFile:recordPath displayName:@"[语音]"];
EMVoiceMessageBody *voiceBody = [[EMVoiceMessageBody alloc] initWithChatObject:chatVoice];
voiceBody.duration = duration;
// 2.构造一个消息对象
EMMessage *msg = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[voiceBody]];
msg.messageType = eMessageTypeChat;
// 3.发送
[[EaseMob sharedInstance].chatManager asyncSendMessage:msg progress:nil prepare:^(EMMessage *message, EMError *error) {
//准备发送语音
} onQueue:nil completion:^(EMMessage *message, EMError *error) {
if (!error) {
//语音发送成功
}else{
//语音发送失败
}
} onQueue:nil];
}