你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS語音書寫功能(語音轉文本)

iOS語音書寫功能(語音轉文本)

編輯:IOS開發綜合

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文件

\

Demo中的APPID

\

添加SDK,及添加關聯framework

\

\

設置Bitcode屬性為 NO

\

 

 

語音轉文件實現代碼

  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. NSRangerange;
  359. NSString*line=[arrayobjectAtIndex:index];
  360.  
  361. NSRangeidRange=[linerangeOfString:@"id="];
  362. NSRangenameRange=[linerangeOfString:@"name="];
  363. NSRangeconfidenceRange=[linerangeOfString:@"confidence="];
  364. NSRangegrammarRange=[linerangeOfString:@"grammar="];
  365.  
  366. NSRangeinputRange=[linerangeOfString:@"input="];
  367.  
  368. if(confidenceRange.length==0||grammarRange.length==0||inputRange.length==0)
  369. {
  370. continue;
  371. }
  372.  
  373. //checknomatch
  374. if(idRange.length!=0)
  375. {
  376. NSUIntegeridPosX=idRange.location+idRange.length;
  377. NSUIntegeridLength=nameRange.location-idPosX;
  378. range=NSMakeRange(idPosX,idLength);
  379.  
  380. NSString*subString=[linesubstringWithRange:range];
  381. NSCharacterSet*subSet=[NSCharacterSetwhitespaceAndNewlineCharacterSet];
  382. NSString*idValue=[subStringstringByTrimmingCharactersInSet:subSet];
  383. if([idValueisEqualToString:@"nomatch"])
  384. {
  385. return@"";
  386. }
  387. }
  388.  
  389. //GetConfidenceValue
  390. NSUIntegerconfidencePosX=confidenceRange.location+confidenceRange.length;
  391. NSUIntegerconfidenceLength=grammarRange.location-confidencePosX;
  392. range=NSMakeRange(confidencePosX,confidenceLength);
  393.  
  394. NSString*score=[linesubstringWithRange:range];
  395.  
  396. NSUIntegerinputStringPosX=inputRange.location+inputRange.length;
  397. NSUIntegerinputStringLength=line.length-inputStringPosX;
  398.  
  399. range=NSMakeRange(inputStringPosX,inputStringLength);
  400. inputString=[linesubstringWithRange:range];
  401.  
  402. [resultStringappendFormat:@"%@置信度%@\n",inputString,score];
  403. }
  404.  
  405. returnresultString;
  406. }
  407.  
  408. /**
  409. 解析聽寫json格式的數據
  410. params例如:
  411. {"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}]}]}
  412. */
  413. +(NSString*)stringFromJson:(NSString*)params
  414. {
  415. if(params==NULL)
  416. {
  417. returnnil;
  418. }
  419.  
  420. NSMutableString*tempStr=[[NSMutableStringalloc]init];
  421. //返回的格式必須為utf8的,否則發生未知錯誤
  422. NSData*dataJSON=[paramsdataUsingEncoding:NSUTF8StringEncoding];
  423. NSDictionary*resultDic=[NSJSONSerializationJSONObjectWithData:dataJSONoptions:kNilOptionserror:nil];
  424.  
  425. if(resultDic!=nil)
  426. {
  427. NSArray*wordArray=[resultDicobjectForKey:@"ws"];
  428.  
  429. for(inti=0;i<[wordArraycount];i++)
  430. {
  431. NSDictionary*wsDic=[wordArrayobjectAtIndex:i];
  432. NSArray*cwArray=[wsDicobjectForKey:@"cw"];
  433.  
  434. for(intj=0;j<[cwArraycount];j++)
  435. {
  436. NSDictionary*wDic=[cwArrayobjectAtIndex:j];
  437. NSString*str=[wDicobjectForKey:@"w"];
  438. [tempStrappendString:str];
  439. }
  440. }
  441. }
  442.  
  443. returntempStr;
  444. }
  445.  
  446.  
  447. /**
  448. 解析語法識別返回的結果
  449. */
  450. +(NSString*)stringFromABNFJson:(NSString*)params
  451. {
  452. if(params==NULL)
  453. {
  454. returnnil;
  455. }
  456. NSMutableString*tempStr=[[NSMutableStringalloc]init];
  457. NSData*dataJSON=[paramsdataUsingEncoding:NSUTF8StringEncoding];
  458. NSDictionary*resultDic=[NSJSONSerializationJSONObjectWithData:dataJSONoptions:kNilOptionserror:nil];
  459.  
  460. NSArray*wordArray=[resultDicobjectForKey:@"ws"];
  461. for(inti=0;i<[wordArraycount];i++)
  462. {
  463. NSDictionary*wsDic=[wordArrayobjectAtIndex:i];
  464. NSArray*cwArray=[wsDicobjectForKey:@"cw"];
  465.  
  466. for(intj=0;j<[cwArraycount];j++)
  467. {
  468. NSDictionary*wDic=[cwArrayobjectAtIndex:j];
  469. NSString*str=[wDicobjectForKey:@"w"];
  470. NSString*score=[wDicobjectForKey:@"sc"];
  471. [tempStrappendString:str];
  472. [tempStrappendFormat:@"置信度:%@",score];
  473. [tempStrappendString:@"\n"];
  474. }
  475. }
  476.  
  477. returntempStr;
  478. }
  479.  
  480. /**************************************************************************/
  481.  
  482. @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
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved