iOS开发项目- 基于WebSocket的聊天通讯(2)
程序员文章站
2023-12-19 18:41:52
公司项目需要开发一个类似qq、微信的即时im聊天功能,做到实时监控消息,需要用的技术是websocket,今天整理下语言聊天这块;其实语言聊天,包含两部分,录音和音乐播放,...
公司项目需要开发一个类似qq、微信的即时im聊天功能,做到实时监控消息,需要用的技术是websocket,今天整理下语言聊天这块;其实语言聊天,包含两部分,录音和音乐播放,关于简单语言聊天功能如下图:
录音
在avfoundation框架中有一个avaudiorecorder类专门处理录音操作,它同样支持多种音频格式。与avaudioplayer类似,你完全可以将它看成是一个录音机控制类,下面是常用的属性和方法:
先来了解下avaudiorecorder的常用属性:
@property (readonly, getter=isrecording) bool recording;//是否正在录音 @property (readonly) nsdictionary<nsstring *, id> *settings;//录音配置 @property (readonly) nsurl *url;//录音文件存放url @property (readonly) nstimeinterval currenttime;//录音时长 @property (getter=ismeteringenabled) bool meteringenabled;//是否监控声波
常用对象方法:
- (bool)preparetorecord;//为录音准备缓冲区 - (bool)record;//录音开始,暂停后调用会恢复录音 - (bool)recordattime:(nstimeinterval)time;//在指定时间后开始录音 - (bool)recordforduration:(nstimeinterval) duration;//按指定时长录音 - (bool)recordattime:(nstimeinterval)time forduration:(nstimeinterval)duration;//上面2个的合体 - (void)pause; //中断录音 - (void)stop; //停止录音 - (bool)deleterecording;//删除录音,必须先停止录音再删除
常用的代理方法:
//录音完成后调用 - (void)audiorecorderdidfinishrecording:(avaudiorecorder *)recorder successfully:(bool)flag;//录音编码发送错误时调用 - (void)audiorecorderencodeerrordidoccur:(avaudiorecorder *)recorder error:(nserror *)error;
音频
如果播放较大的音频或者要对音频有精确的控制则system sound service可能就很难满足实际需求了,通常这种情况会选择使用avfoundation.framework中的avaudioplayer来实现。avaudioplayer可以看成一个播放器,它支持多种音频格式,而且能够进行进度、音量、播放速度等控制
avaudioplayer的使用比较简单:
1.初始化avaudioplayer对象,此时通常指定本地文件路径。
2.设置播放器属性,例如重复次数、音量大小等。
3.调用play方法播放。
具体实现代码
#import <avfoundation/avfoundation.h> #define krecordaudiofile @"myrecord.caf" @interface viewcontroller ()<avaudiorecorderdelegate> { nsstring *datename; } @property (weak, nonatomic) iboutlet uitableview *table; @property (nonatomic,strong) avaudiorecorder *audiorecorder;//音频录音机 @property (nonatomic,strong) avaudioplayer *audioplayer;//音频播放器,用于播放录音文件 @property(nonatomic,strong) nsmutablearray *spacedata; @end @implementation viewcontroller #pragma mark - 私有方法 /** * 设置音频会话 */ -(void)setaudiosession{ avaudiosession *audiosession=[avaudiosession sharedinstance]; //设置为播放和录音状态,以便可以在录制完之后播放录音 [audiosession setcategory:avaudiosessioncategoryplayandrecord error:nil]; [audiosession setactive:yes error:nil]; } /** * 取得录音文件设置 * * @return 录音设置 */ -(nsdictionary *)getaudiosetting{ nsmutabledictionary *dicm=[nsmutabledictionary dictionary]; //设置录音格式 [dicm setobject:@(kaudioformatlinearpcm) forkey:avformatidkey]; //设置录音采样率,8000是电话采样率,对于一般录音已经够了 [dicm setobject:@(8000) forkey:avsampleratekey]; //设置通道,这里采用单声道 [dicm setobject:@(1) forkey:avnumberofchannelskey]; //每个采样点位数,分为8、16、24、32 [dicm setobject:@(8) forkey:avlinearpcmbitdepthkey]; //是否使用浮点数采样 [dicm setobject:@(yes) forkey:avlinearpcmisfloatkey]; //....其他设置等 return dicm; } /** * 取得录音文件保存路径 * * @return 录音文件路径 */ -(nsurl *)getplaypath:(nsstring *)title{ // static int index = 0; nsstring *urlstr=[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) lastobject]; urlstr=[urlstr stringbyappendingpathcomponent:[nsstring stringwithformat:@"%@%@",title,krecordaudiofile]]; nslog(@"play file path:%@",urlstr); nsurl *url=[nsurl fileurlwithpath:urlstr]; return url; } /** * 以日期为title,来保存录音 * * @return <#return value description#> */ - (nsstring *) convertdatefromstring { nsdate *date = [nsdate date]; // nslog(@"%@--askl",date); // nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; //zzz表示时区,zzz可以删除,这样返回的日期字符将不包含时区信息。 [dateformatter setdateformat:@"yyyy-mm-dd hh:mm:ss"]; nsstring *destdatestring = [dateformatter stringfromdate:date]; return destdatestring; }
长按录音,松开停止
- (void)setclikespacestate:(nsstring *)astate { nslog(@"点击语音---"); if([astate isequaltostring:@"begin"]) { nslog(@"begin---"); datename = [self convertdatefromstring]; //创建录音文件保存路径 nsurl *url=[self getplaypath:datename]; //创建录音格式设置 nsdictionary *setting=[self getaudiosetting]; //创建录音机 nserror *error=nil; _audiorecorder=[[avaudiorecorder alloc]initwithurl:url settings:setting error:&error]; _audiorecorder.delegate=self; _audiorecorder.meteringenabled=yes;//如果要监控声波则必须设置为yes if (![self.audiorecorder isrecording]) { [self.audiorecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风 // self.timer.firedate=[nsdate distantpast]; nslog(@"111"); } }else { nslog(@"end---"); /** 停止录音*/ [self.audiorecorder stop]; /** 录音地址*/ nsurl *url = [self getplaypath:datename]; /** 加载数据*/ avaudioplayer *audioplayer1 = [[avaudioplayer alloc] initwithcontentsofurl:url error:nil]; model *model = [[model alloc]init]; model.duration = [nsstring stringwithformat:@"%.f",audioplayer1.duration]; model.spacepath = datename; /** table 刷新*/ [self.spacedata addobject:model]; [self.table reloaddata]; /** table 滚动到当前row*/ [self.table selectrowatindexpath:[nsindexpath indexpathforrow:(self.spacedata.count - 1) insection:0] animated:yes scrollposition:uitableviewscrollpositiontop]; } }
点击table 播放
- (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath{ model *model = self.spacedata[indexpath.row]; /** 播放录音*/ nsurl *url=[self getplaypath:model.spacepath]; nserror *error=nil; _audioplayer=[[avaudioplayer alloc]initwithcontentsofurl:url error:&error]; _audioplayer.numberofloops=0; [_audioplayer preparetoplay]; [self.audioplayer play]; nslog(@"%.0f---aaaa",_audioplayer.duration); /** uiimage动画数组*/ nsmutablearray *imgdata = [nsmutablearray array]; for(int i=0;i<4;i++) { uiimage *aimage = [uiimage imagenamed:[nsstring stringwithformat:@"chat_receiver_audio_playing00%d",i]]; [imgdata addobject:aimage]; } twotableviewcell *twocell = [self.table cellforrowatindexpath:indexpath]; /** 点击动画*/ [twocell.speak setanimationimages:imgdata]; // [twocell.speak setanimationrepeatcount:1]; [twocell.speak setanimationduration:1]; [twocell.speak startanimating]; dispatch_after(dispatch_time(dispatch_time_now, (int64_t)([model.duration intvalue] * nsec_per_sec)), dispatch_get_main_queue(), ^{ [twocell.speak stopanimating]; }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。