欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS语音书写功能(语音转文本)

程序员文章站 2022-04-22 10:58:06
Demo下载地址 最近在项目开发中,需要将语音识别转换成文本的功能。研究了下科大讯飞,附上Demo分享给大家。 研发前先得做一些准备。 1、注册科大讯飞开发者帐号(http:...

Demo下载地址

最近在项目开发中,需要将语音识别转换成文本的功能。研究了下科大讯飞,附上Demo分享给大家。

研发前先得做一些准备。

1、注册科大讯飞开发者帐号(http://www.xfyun.cn

2、下载开发平台(iOS、或Android,或其他)所需要的SDK(SDK包含:说明文档、SDK即iflyMSC.framework、Demo)

3、项目中添加SDK(添加时,先将SDK复制粘贴到项目文件,再通过addframe的方法添加到项目引用),及相关联的framework

添加方法:TARGETS-Build Phases-Link Binary With Libraries-"+"-Choose frameworks and libraries to add-add other,或选择对应的framework-add

4、使用时要添加对应的头文件

特别说明:

1、使用SDK关联的APPID存在于下载的Demo中,如果SDK有替换的话APPID应该跟着一起替换。

2、添加其他framework:

libz.tbd

libc++.tbd

CoreGraphics.framework

QuartzCore.framework

AddressBook.framework

CoreLocation.framework

UIKit.framework

AudioToolbox.framework

Foundation.framework

SystemConfiguration.framework

AVFoundation.framework

CoreTelephoney.framework

3、Bitcode属性设置为NO(TARGETS-Build Settings-Build Options-Enable Bitcode-NO)

4、在使用前,务必在AppDelegate的方法中"

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {}"进行初始化操作。

5、需要有网络的情况下才能使用。

如图

下载的科大讯飞SDK文件

iOS语音书写功能(语音转文本)

Demo中的APPID

iOS语音书写功能(语音转文本)

添加SDK,及添加关联framework

iOS语音书写功能(语音转文本)

iOS语音书写功能(语音转文本)

设置Bitcode属性为 NO

iOS语音书写功能(语音转文本)

 

 

语音转文件实现代码

  1. .h文件
  2.  
  3. #import
  4.  
  5. //导入头文件
  6. #import"iflyMSC.framework/Headers/IFlyMSC.h"
  7. #import"iflyMSC.framework/Headers/IFlySpeechUtility.h"
  8. #import"iflyMSC/IFlySpeechConstant.h"
  9.  
  10.  
  11. #pragmamark-初始化参数类
  12.  
  13. /**************************************************************************/
  14.  
  15. @interfaceIATConfig:NSObject
  16.  
  17. +(IATConfig*)sharedInstance;
  18.  
  19. +(NSString*)mandarin;
  20. +(NSString*)cantonese;
  21. +(NSString*)henanese;
  22. +(NSString*)chinese;
  23. +(NSString*)english;
  24. +(NSString*)lowSampleRate;
  25. +(NSString*)highSampleRate;
  26. +(NSString*)isDot;
  27. +(NSString*)noDot;
  28.  
  29.  
  30. /**
  31. 以下参数,需要通过iFlySpeechRecgonizer进行设置
  32. */
  33. @property(nonatomic,strong)NSString*speechTimeout;
  34. @property(nonatomic,strong)NSString*vadEos;
  35. @property(nonatomic,strong)NSString*vadBos;
  36.  
  37. @property(nonatomic,strong)NSString*language;
  38. @property(nonatomic,strong)NSString*accent;
  39.  
  40. @property(nonatomic,strong)NSString*dot;
  41. @property(nonatomic,strong)NSString*sampleRate;
  42.  
  43.  
  44. /**
  45. 以下参数无需设置不必关
  46. */
  47. @property(nonatomic,assign)BOOLhaveView;
  48. @property(nonatomic,strong)NSArray*accentIdentifer;
  49. @property(nonatomic,strong)NSArray*accentNickName;
  50.  
  51. @end
  52.  
  53. /**************************************************************************/
  54.  
  55.  
  56. #pragmamark-语音听写类
  57.  
  58. @interfaceVoiceConversion:NSObject
  59.  
  60. ///启动初始化语音程序
  61. +(void)VoiceInitialize;
  62.  
  63.  
  64. ///开始录音
  65. -(void)voiceStart:(void(^)(BOOLisStart))startListening
  66. speechBegin:(void(^)(void))begin
  67. speechEnd:(void(^)(void))end
  68. speechError:(void(^)(BOOLisSuccess))error
  69. speechResult:(void(^)(NSString*text))result
  70. speechVolume:(void(^)(intvolume))volume;
  71.  
  72. ///取消录音
  73. -(void)voiceCancel;
  74.  
  75. ///停止录音
  76. -(void)voiceStop;
  77.  
  78. @end

 

  1. .m文件
  2.  
  3. #import"VoiceConversion.h"
  4.  
  5. #pragmamark-初始化参数类
  6.  
  7. /**************************************************************************/
  8.  
  9. staticNSString*constPUTONGHUA=@"mandarin";
  10. staticNSString*constYUEYU=@"cantonese";
  11. staticNSString*constHENANHUA=@"henanese";
  12. staticNSString*constENGLISH=@"en_us";
  13. staticNSString*constCHINESE=@"zh_cn";
  14.  
  15. @implementationIATConfig
  16.  
  17. -(id)init
  18. {
  19. self=[superinit];
  20. if(self)
  21. {
  22. [selfdefaultSetting];
  23. returnself;
  24. }
  25. returnnil;
  26. }
  27.  
  28. +(IATConfig*)sharedInstance
  29. {
  30. staticIATConfig*instance=nil;
  31. staticdispatch_once_tpredict;
  32. dispatch_once(&predict,^{
  33. instance=[[IATConfigalloc]init];
  34. });
  35. returninstance;
  36. }
  37.  
  38. -(void)defaultSetting
  39. {
  40. _speechTimeout=@"30000";
  41. _vadEos=@"3000";
  42. _vadBos=@"3000";
  43. _dot=@"1";
  44. _sampleRate=@"16000";
  45. _language=CHINESE;
  46. _accent=PUTONGHUA;
  47. _haveView=NO;//默认是不dai界面的
  48. _accentNickName=[[NSArrayalloc]initWithObjects:@"粤语",@"普通话",@"河南话",@"英文",nil];
  49. }
  50.  
  51. +(NSString*)mandarin
  52. {
  53. returnPUTONGHUA;
  54. }
  55.  
  56. +(NSString*)cantonese
  57. {
  58. returnYUEYU;
  59. }
  60.  
  61. +(NSString*)henanese
  62. {
  63. returnHENANHUA;
  64. }
  65.  
  66. +(NSString*)chinese
  67. {
  68. returnCHINESE;
  69. }
  70.  
  71. +(NSString*)english
  72. {
  73. returnENGLISH;
  74. }
  75.  
  76. +(NSString*)lowSampleRate
  77. {
  78. return@"8000";
  79. }
  80.  
  81. +(NSString*)highSampleRate
  82. {
  83. return@"16000";
  84. }
  85.  
  86. +(NSString*)isDot
  87. {
  88. return@"1";
  89. }
  90.  
  91. +(NSString*)noDot
  92. {
  93. return@"0";
  94. }
  95.  
  96. @end
  97.  
  98. /**************************************************************************/
  99.  
  100. #pragmamark-语音听写类
  101.  
  102. staticNSString*constVoiceAPPID=@"572016e4";
  103. staticNSString*constVoiceTimeOut=@"20000";
  104.  
  105. @interfaceVoiceConversion()
  106.  
  107. @property(nonatomic,strong)NSMutableString*resultText;
  108. @property(nonatomic,strong)IFlySpeechRecognizer*iFlySpeechRecognizer;
  109.  
  110. @property(nonatomic,copy)void(^beginSpeech)(void);
  111. @property(nonatomic,copy)void(^endSpeech)(void);
  112. @property(nonatomic,copy)void(^errorSpeech)(BOOLisSuccess);
  113. @property(nonatomic,copy)void(^resultSpeech)(NSString*text);
  114. @property(nonatomic,copy)void(^volumeSpeech)(intvolume);
  115.  
  116. @end
  117.  
  118. @implementationVoiceConversion
  119.  
  120. #pragmamark初始化------------
  121.  
  122. ///启动初始化语音程序
  123. +(void)VoiceInitialize
  124. {
  125. //设置sdk的log等级,log保存在下面设置的工作路径中
  126. [IFlySettingsetLogFile:LVL_ALL];
  127.  
  128. //打开输出在console的log开关
  129. [IFlySettingshowLogcat:YES];
  130.  
  131. //设置sdk的工作路径
  132. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
  133. NSString*cachePath=[pathsobjectAtIndex:0];
  134. [IFlySettingsetLogFilePath:cachePath];
  135.  
  136. //Appid是应用的身份信息,具有唯一性,初始化时必须要传入Appid。初始化是一个异步过程,可放在App启动时执行初始化,具体代码可以参照Demo的MSCAppDelegate.m。未初始化时使用服务,一般会返回错误码10111.
  137. NSString*initString=[[NSStringalloc]initWithFormat:@"appid=%@",VoiceAPPID];
  138. [IFlySpeechUtilitycreateUtility:initString];
  139. }
  140.  
  141. #pragmamark实例化------------
  142.  
  143. -(void)dealloc
  144. {
  145. [selfvoiceCancel];
  146. }
  147.  
  148. -(NSMutableString*)resultText
  149. {
  150. if(!_resultText)
  151. {
  152. _resultText=[[NSMutableStringalloc]init];
  153. }
  154.  
  155. return_resultText;
  156. }
  157.  
  158. -(IFlySpeechRecognizer*)iFlySpeechRecognizer
  159. {
  160. if(_iFlySpeechRecognizer==nil)
  161. {
  162. _iFlySpeechRecognizer=[IFlySpeechRecognizersharedInstance];
  163.  
  164. [_iFlySpeechRecognizersetParameter:@""forKey:[IFlySpeechConstantPARAMS]];
  165. //设置听写模式
  166. [_iFlySpeechRecognizersetParameter:@"iat"forKey:[IFlySpeechConstantIFLY_DOMAIN]];
  167. }
  168.  
  169. return_iFlySpeechRecognizer;
  170. }
  171.  
  172. -(void)initializeVoice
  173. {
  174. self.iFlySpeechRecognizer.delegate=self;
  175.  
  176. IATConfig*instance=[IATConfigsharedInstance];
  177.  
  178. //设置最长录音时间
  179. [self.iFlySpeechRecognizersetParameter:instance.speechTimeoutforKey:[IFlySpeechConstantSPEECH_TIMEOUT]];
  180. //设置后端点
  181. [self.iFlySpeechRecognizersetParameter:instance.vadEosforKey:[IFlySpeechConstantVAD_EOS]];
  182. //设置前端点
  183. [self.iFlySpeechRecognizersetParameter:instance.vadBosforKey:[IFlySpeechConstantVAD_BOS]];
  184. //网络等待时间
  185. [self.iFlySpeechRecognizersetParameter:@"20000"forKey:[IFlySpeechConstantNET_TIMEOUT]];
  186.  
  187. //设置采样率,推荐使用16K
  188. [self.iFlySpeechRecognizersetParameter:instance.sampleRateforKey:[IFlySpeechConstantSAMPLE_RATE]];
  189.  
  190. if([instance.languageisEqualToString:[IATConfigchinese]])
  191. {
  192. //设置语言
  193. [self.iFlySpeechRecognizersetParameter:instance.languageforKey:[IFlySpeechConstantLANGUAGE]];
  194. //设置方言
  195. [self.iFlySpeechRecognizersetParameter:instance.accentforKey:[IFlySpeechConstantACCENT]];
  196. }
  197. elseif([instance.languageisEqualToString:[IATConfigenglish]])
  198. {
  199. [self.iFlySpeechRecognizersetParameter:instance.languageforKey:[IFlySpeechConstantLANGUAGE]];
  200. }
  201.  
  202. //设置是否返回标点符号
  203. [self.iFlySpeechRecognizersetParameter:instance.dotforKey:[IFlySpeechConstantASR_PTT]];
  204. }
  205.  
  206. #pragmamark语音听写方法------------
  207.  
  208. ///开始录音
  209. -(void)voiceStart:(void(^)(BOOLisStart))startListening
  210. speechBegin:(void(^)(void))begin
  211. speechEnd:(void(^)(void))end
  212. speechError:(void(^)(BOOLisSuccess))error
  213. speechResult:(void(^)(NSString*text))result
  214. speechVolume:(void(^)(intvolume))volume
  215. {
  216. [self.resultTextsetString:@""];
  217.  
  218. //回调设置
  219. self.beginSpeech=[begincopy];
  220. self.endSpeech=[endcopy];
  221. self.errorSpeech=[errorcopy];
  222. self.resultSpeech=[resultcopy];
  223. self.volumeSpeech=[volumecopy];
  224.  
  225.  
  226. //初始化设置
  227. [selfinitializeVoice];
  228.  
  229. [self.iFlySpeechRecognizercancel];
  230.  
  231. //设置音频来源为麦克风
  232. [self.iFlySpeechRecognizersetParameter:IFLY_AUDIO_SOURCE_MICforKey:@"audio_source"];
  233.  
  234. //设置听写结果格式为json
  235. [self.iFlySpeechRecognizersetParameter:@"json"forKey:[IFlySpeechConstantRESULT_TYPE]];
  236.  
  237. //保存录音文件,保存在sdk工作路径中,如未设置工作路径,则默认保存在library/cache下
  238. [self.iFlySpeechRecognizersetParameter:@"asr.pcm"forKey:[IFlySpeechConstantASR_AUDIO_PATH]];
  239.  
  240. BOOLisStart=[self.iFlySpeechRecognizerstartListening];
  241. if(startListening)
  242. {
  243. //如果开始录音失败,可能是上次请求未结束,暂不支持多路并发
  244. startListening(isStart);
  245. }
  246. }
  247.  
  248. ///取消听写
  249. -(void)voiceCancel
  250. {
  251. [self.iFlySpeechRecognizercancel];
  252. }
  253.  
  254. ///停止录音
  255. -(void)voiceStop
  256. {
  257. [self.iFlySpeechRecognizerstopListening];
  258. }
  259.  
  260. #pragmamarkIFlySpeechRecognizerDelegate------------
  261.  
  262. /**
  263. 识别结果返回代理
  264. @param:results识别结果
  265. @param:isLast表示是否最后一次结果
  266. */
  267. -(void)onResults:(NSArray*)resultsisLast:(BOOL)isLast
  268. {
  269. NSMutableString*resultString=[[NSMutableStringalloc]init];
  270. NSDictionary*dic=results[0];
  271. for(NSString*keyindic)
  272. {
  273. [resultStringappendFormat:@"%@",key];
  274. }
  275. NSString*resultFromJson=[[selfclass]stringFromJson:resultString];
  276. NSString*resultTextTemp=[NSStringstringWithFormat:@"%@%@",self.resultText,resultFromJson];
  277. [self.resultTextsetString:resultTextTemp];
  278. if(isLast)
  279. {
  280. if(self.resultSpeech)
  281. {
  282. //去掉最后一个句号
  283. NSRangerange=[self.resultTextrangeOfString:@"。"options:NSBackwardsSearch];
  284. if(range.location!=NSNotFound)
  285. {
  286. resultTextTemp=[self.resultTextsubstringToIndex:range.location];
  287. [self.resultTextsetString:resultTextTemp];
  288. }
  289. self.resultSpeech(self.resultText);
  290. }
  291. }
  292.  
  293. [selfvoiceCancel];
  294. }
  295.  
  296. /**
  297. 识别会话结束返回代理
  298. @paramerror错误码,error.errorCode=0表示正常结束,非0表示发生错误。
  299. */
  300. -(void)onError:(IFlySpeechError*)error
  301. {
  302. if(self.errorSpeech)
  303. {
  304. BOOLisSuccess=(0==error.errorCode);
  305. self.errorSpeech(isSuccess);
  306. }
  307. }
  308.  
  309. /**
  310. 停止录音回调
  311. */
  312. -(void)onEndOfSpeech
  313. {
  314. if(self.endSpeech)
  315. {
  316. self.endSpeech();
  317. }
  318. }
  319.  
  320. /**
  321. 开始识别回调
  322. */
  323. -(void)onBeginOfSpeech
  324. {
  325. if(self.beginSpeech)
  326. {
  327. self.beginSpeech();
  328. }
  329. }
  330.  
  331. /**
  332. 音量回调函数volume0-30
  333. */
  334. -(void)onVolumeChanged:(int)volume
  335. {
  336. if(self.volumeSpeech)
  337. {
  338. self.volumeSpeech(volume);
  339. }
  340. }
  341.  
  342.  
  343. #pragmamark解析方法------------
  344.  
  345. /**************************************************************************/
  346.  
  347. /**
  348. 解析命令词返回的结果
  349. */
  350. +(NSString*)stringFromAsr:(NSString*)params;
  351. {
  352. NSMutableString*resultString=[[NSMutableStringalloc]init];
  353. NSString*inputString=nil;
  354.  
  355. NSArray*array=[paramscomponentsSeparatedByString:@"\n"];
  356.  
  357. for(intindex=0;index
  358. {
  359. NSRangerange;
  360. NSString*line=[arrayobjectAtIndex:index];
  361.  
  362. NSRangeidRange=[linerangeOfString:@"id="];
  363. NSRangenameRange=[linerangeOfString:@"name="];
  364. NSRangeconfidenceRange=[linerangeOfString:@"confidence="];
  365. NSRangegrammarRange=[linerangeOfString:@"grammar="];
  366.  
  367. NSRangeinputRange=[linerangeOfString:@"input="];
  368.  
  369. if(confidenceRange.length==0||grammarRange.length==0||inputRange.length==0)
  370. {
  371. continue;
  372. }
  373.  
  374. //checknomatch
  375. if(idRange.length!=0)
  376. {
  377. NSUIntegeridPosX=idRange.location+idRange.length;
  378. NSUIntegeridLength=nameRange.location-idPosX;
  379. range=NSMakeRange(idPosX,idLength);
  380.  
  381. NSString*subString=[linesubstringWithRange:range];
  382. NSCharacterSet*subSet=[NSCharacterSetwhitespaceAndNewlineCharacterSet];
  383. NSString*idValue=[subStringstringByTrimmingCharactersInSet:subSet];
  384. if([idValueisEqualToString:@"nomatch"])
  385. {
  386. return@"";
  387. }
  388. }
  389.  
  390. //GetConfidenceValue
  391. NSUIntegerconfidencePosX=confidenceRange.location+confidenceRange.length;
  392. NSUIntegerconfidenceLength=grammarRange.location-confidencePosX;
  393. range=NSMakeRange(confidencePosX,confidenceLength);
  394.  
  395. NSString*score=[linesubstringWithRange:range];
  396.  
  397. NSUIntegerinputStringPosX=inputRange.location+inputRange.length;
  398. NSUIntegerinputStringLength=line.length-inputStringPosX;
  399.  
  400. range=NSMakeRange(inputStringPosX,inputStringLength);
  401. inputString=[linesubstringWithRange:range];
  402.  
  403. [resultStringappendFormat:@"%@置信度%@\n",inputString,score];
  404. }
  405.  
  406. returnresultString;
  407. }
  408.  
  409. /**
  410. 解析听写json格式的数据
  411. params例如:
  412. {"sn":1,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"w":"白日","sc":0}]},{"bg":0,"cw":[{"w":"依山","sc":0}]},{"bg":0,"cw":[{"w":"尽","sc":0}]},{"bg":0,"cw":[{"w":"黄河入海流","sc":0}]},{"bg":0,"cw":[{"w":"。","sc":0}]}]}
  413. */
  414. +(NSString*)stringFromJson:(NSString*)params
  415. {
  416. if(params==NULL)
  417. {
  418. returnnil;
  419. }
  420.  
  421. NSMutableString*tempStr=[[NSMutableStringalloc]init];
  422. //返回的格式必须为utf8的,否则发生未知错误
  423. NSData*dataJSON=[paramsdataUsingEncoding:NSUTF8StringEncoding];
  424. NSDictionary*resultDic=[NSJSONSerializationJSONObjectWithData:dataJSONoptions:kNilOptionserror:nil];
  425.  
  426. if(resultDic!=nil)
  427. {
  428. NSArray*wordArray=[resultDicobjectForKey:@"ws"];
  429.  
  430. for(inti=0;i<[wordArraycount];i++)
  431. {
  432. NSDictionary*wsDic=[wordArrayobjectAtIndex:i];
  433. NSArray*cwArray=[wsDicobjectForKey:@"cw"];
  434.  
  435. for(intj=0;j<[cwArraycount];j++)
  436. {
  437. NSDictionary*wDic=[cwArrayobjectAtIndex:j];
  438. NSString*str=[wDicobjectForKey:@"w"];
  439. [tempStrappendString:str];
  440. }
  441. }
  442. }
  443.  
  444. returntempStr;
  445. }
  446.  
  447.  
  448. /**
  449. 解析语法识别返回的结果
  450. */
  451. +(NSString*)stringFromABNFJson:(NSString*)params
  452. {
  453. if(params==NULL)
  454. {
  455. returnnil;
  456. }
  457. NSMutableString*tempStr=[[NSMutableStringalloc]init];
  458. NSData*dataJSON=[paramsdataUsingEncoding:NSUTF8StringEncoding];
  459. NSDictionary*resultDic=[NSJSONSerializationJSONObjectWithData:dataJSONoptions:kNilOptionserror:nil];
  460.  
  461. NSArray*wordArray=[resultDicobjectForKey:@"ws"];
  462. for(inti=0;i<[wordArraycount];i++)
  463. {
  464. NSDictionary*wsDic=[wordArrayobjectAtIndex:i];
  465. NSArray*cwArray=[wsDicobjectForKey:@"cw"];
  466.  
  467. for(intj=0;j<[cwArraycount];j++)
  468. {
  469. NSDictionary*wDic=[cwArrayobjectAtIndex:j];
  470. NSString*str=[wDicobjectForKey:@"w"];
  471. NSString*score=[wDicobjectForKey:@"sc"];
  472. [tempStrappendString:str];
  473. [tempStrappendFormat:@"置信度:%@",score];
  474. [tempStrappendString:@"\n"];
  475. }
  476. }
  477.  
  478. returntempStr;
  479. }
  480.  
  481. /**************************************************************************/
  482.  
  483. @end


使用

  1. 初始化方法
  2. ///启动初始化语音程序
  3. +(void)VoiceInitialize
  4. {
  5. //设置sdk的log等级,log保存在下面设置的工作路径中
  6. [IFlySettingsetLogFile:LVL_ALL];
  7.  
  8. //打开输出在console的log开关
  9. [IFlySettingshowLogcat:YES];
  10.  
  11. //设置sdk的工作路径
  12. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
  13. NSString*cachePath=[pathsobjectAtIndex:0];
  14. [IFlySettingsetLogFilePath:cachePath];
  15.  
  16. //Appid是应用的身份信息,具有唯一性,初始化时必须要传入Appid。初始化是一个异步过程,可放在App启动时执行初始化,具体代码可以参照Demo的MSCAppDelegate.m。未初始化时使用服务,一般会返回错误码10111.
  17. NSString*initString=[[NSStringalloc]initWithFormat:@"appid=%@",VoiceAPPID];
  18. [IFlySpeechUtilitycreateUtility:initString];
  19. }
  20.  
  21. 初始化调用
  22. -(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  23. {
  24. //Overridepointforcustomizationafterapplicationlaunch.
  25.  
  26. [VoiceConversionVoiceInitialize];
  27.  
  28. returnYES;
  29. }
  30. #import"VoiceConversion.h"
  31.  
  32. @interfaceViewController()
  33.  
  34. @property(nonatomic,strong)VoiceConversion*voiceConversion;
  35. @property(nonatomic,strong)UILabel*messageLabel;
  36.  
  37. @end
  38.  
  39. @implementationViewController
  40.  
  41. -(void)viewDidLoad{
  42. [superviewDidLoad];
  43. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  44.  
  45. UIBarButtonItem*startItem=[[UIBarButtonItemalloc]initWithTitle:@"start"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(startItemClick:)];
  46. UIBarButtonItem*stopItem=[[UIBarButtonItemalloc]initWithTitle:@"stop"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(stopItemClick:)];
  47. UIBarButtonItem*cancelItem=[[UIBarButtonItemalloc]initWithTitle:@"cancel"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(cancelItemClick:)];
  48. self.navigationItem.rightBarButtonItems=@[startItem,stopItem,cancelItem];
  49.  
  50. self.title=@"科大讯飞语音";
  51.  
  52. [selfsetUI];
  53. }
  54.  
  55. -(void)didReceiveMemoryWarning{
  56. [superdidReceiveMemoryWarning];
  57. //Disposeofanyresourcesthatcanberecreated.
  58. }
  59.  
  60. #pragmamark-视图
  61.  
  62. -(void)setUI
  63. {
  64. if([selfrespondsToSelector:@selector(setEdgesForExtendedLayout:)])
  65. {
  66. [selfsetEdgesForExtendedLayout:UIRectEdgeNone];
  67. }
  68.  
  69. self.messageLabel=[[UILabelalloc]initWithFrame:CGRectMake(10.0,10.0,CGRectGetWidth(self.view.bounds)-10.0*2,40.0)];
  70. [self.viewaddSubview:self.messageLabel];
  71. self.messageLabel.backgroundColor=[UIColorcolorWithWhite:0.5alpha:0.3];
  72. self.messageLabel.textAlignment=NSTextAlignmentCenter;
  73. }
  74.  
  75. #pragmamark-响应
  76.  
  77. -(void)startItemClick:(UIBarButtonItem*)item
  78. {
  79. ViewController__weak*weakSelf=self;
  80. [self.voiceConversionvoiceStart:^(BOOLisStart){
  81.  
  82. NSLog(@"1start");
  83.  
  84. if(isStart)
  85. {
  86. weakSelf.messageLabel.text=@"正在录音";
  87. }
  88. else
  89. {
  90. weakSelf.messageLabel.text=@"启动识别服务失败,请稍后重试";
  91. }
  92. }speechBegin:^{
  93. NSLog(@"2begin");
  94. }speechEnd:^{
  95. NSLog(@"3end");
  96. }speechError:^(BOOLisSuccess){
  97. NSLog(@"4error");
  98. }speechResult:^(NSString*text){
  99. NSLog(@"5result");
  100. weakSelf.messageLabel.text=text;
  101. }speechVolume:^(intvolume){
  102. NSLog(@"6volume");
  103. NSString*volumeString=[NSStringstringWithFormat:@"音量:%d",volume];
  104. weakSelf.messageLabel.text=volumeString;
  105. }];
  106. }
  107.  
  108. -(void)stopItemClick:(UIBarButtonItem*)item
  109. {
  110. [self.voiceConversionvoiceStop];
  111.  
  112. self.messageLabel.text=@"停止录音";
  113. }
  114.  
  115. -(void)cancelItemClick:(UIBarButtonItem*)item
  116. {
  117. [self.voiceConversionvoiceCancel];
  118.  
  119. self.messageLabel.text=@"取消识别";
  120. }
  121.  
  122. #pragmamark-getter
  123.  
  124. -(VoiceConversion*)voiceConversion
  125. {
  126. if(!_voiceConversion)
  127. {
  128. _voiceConversion=[[VoiceConversionalloc]init];
  129. }
  130.  
  131. return_voiceConversion;
  132. }
  133.  
  134. @end