1. 程式人生 > >04環信聊天介面

04環信聊天介面

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];
}