您的位置:首页 > 其它

04环信聊天界面 - 播放语音消息

2016-02-20 19:44 435 查看
分析:需要监听messageLabel的点击事件,然后播放

1.在chatCell里给messageLabel添加点击事件
/**
*  初始化
*/
-(void)awakeFromNib
{
// 1.给messageLabel添加手势
self.messageLabel.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(messageLabelTap:)];
[self.messageLabel addGestureRecognizer: tap];
}


/**
*  当用户点击messageLabel播放语言
*/
- (void)messageLabelTap:(UIGestureRecognizer *)recognizer
{
id body = self.message.messageBodies[0];
if ([body isKindOfClass:[EMVoiceMessageBody class]]) {
// 播放语音
BOOL receiver = [self.reuseIdentifier isEqualToString:recivierCell];
[AudioPlayTool playWithMessage:self.message messageLabel:self.messageLabel receiver:receiver];
}
}
2.播放语音的工具类
//
//  AudioPlayTool.h

#import <UIKit/UIKit.h>

@class EMMessage;

@interface AudioPlayTool : NSObject

/**
*  播放语音
*
*  @param message      EMMessage消息
*  @param messageLabel 显示消息的label
*  @param receiver     是否是接收方
*/
+ (void)playWithMessage:(EMMessage *)message messageLabel:(UILabel *)messageLabel receiver:(BOOL)receiver;
@end
//
//  AudioPlayTool.m
//  环信项目

#import "AudioPlayTool.h"
#import "EMCDDeviceManager.h"
#import "EaseMob.h"

/**
*  正在执行动画的imageView
*/
static UIImageView *animatingImageView;

@implementation AudioPlayTool

+ (void)playWithMessage:(EMMessage *)message messageLabel:(UILabel *)messageLabel receiver:(BOOL)receiver
{
// 0.把上个动画移除
[animatingImageView stopAnimating];
[animatingImageView removeFromSuperview];

// 1.播放语音
EMVoiceMessageBody *voiceBody = message.messageBodies[0];
NSString *path = voiceBody.localPath;

NSFileManager *mgr = [NSFileManager defaultManager];
if ([mgr fileExistsAtPath:path] == NO) {
// 如果本地语言文件不存在,使用服务器的
path = voiceBody.remotePath;
}

[[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:path completion:^(NSError *error) {
// 语言播放完成
// 移除动画
[animatingImageView stopAnimating];
[animatingImageView removeFromSuperview];
}];

// 2.添加动画
UIImageView *imgView = [[UIImageView alloc] init];
[messageLabel addSubview:imgView];

if (receiver) {
imgView.frame = CGRectMake(0, 0, 20, 20);
imgView.animationImages = @[
[UIImage imageNamed:@"chat_receiver_audio_playing000"],
[UIImage imageNamed:@"chat_receiver_audio_playing001"],
[UIImage imageNamed:@"chat_receiver_audio_playing002"],
[UIImage imageNamed:@"chat_receiver_audio_playing003"]
];

}else{
imgView.frame = CGRectMake(messageLabel.bounds.size.width-20, 0, 20, 20);
imgView.animationImages = @[
[UIImage imageNamed:@"chat_sender_audio_playing_000"],
[UIImage imageNamed:@"chat_sender_audio_playing_001"],
[UIImage imageNamed:@"chat_sender_audio_playing_002"],
[UIImage imageNamed:@"chat_sender_audio_playing_003"]
];

}

imgView.animationDuration = 1.0;
[imgView startAnimating];
animatingImageView = imgView;
}

@end

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: