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

3Bitcode属性设置为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




语音转文件实现代码

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. .h文件  
  2.  
  3. #import <Foundation/Foundation.h>  
  4.   
  5. // 导入头文件  
  6. #import "iflyMSC.framework/Headers/IFlyMSC.h"  
  7. #import "iflyMSC.framework/Headers/IFlySpeechUtility.h"  
  8. #import "iflyMSC/IFlySpeechConstant.h"  
  9.  
  10.  
  11. #pragma mark - 初始化参数类  
  12.   
  13. /**************************************************************************/  
  14.   
  15. @interface IATConfig : 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) BOOL haveView;  
  48. @property (nonatomic, strong) NSArray *accentIdentifer;  
  49. @property (nonatomic, strong) NSArray *accentNickName;  
  50.   
  51. @end  
  52.   
  53. /**************************************************************************/  
  54.  
  55.  
  56. #pragma mark - 语音听写类  
  57.   
  58. @interface VoiceConversion : NSObject  
  59.   
  60. /// 启动初始化语音程序  
  61. + (void)VoiceInitialize;  
  62.   
  63.   
  64. /// 开始录音  
  65. - (void)voiceStart:(void (^)(BOOL isStart))startListening   
  66.        speechBegin:(void (^)(void))begin   
  67.          speechEnd:(void (^)(void))end   
  68.        speechError:(void (^)(BOOL isSuccess))error   
  69.       speechResult:(void (^)(NSString *text))result   
  70.       speechVolume:(void (^)(int volume))volume;  
  71.   
  72. /// 取消录音  
  73. - (void)voiceCancel;  
  74.   
  75. /// 停止录音  
  76. - (void)voiceStop;  
  77.   
  78. @end  

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. .m文件  
  2.  
  3. #import "VoiceConversion.h"  
  4.  
  5. #pragma mark - 初始化参数类  
  6.   
  7. /**************************************************************************/  
  8.   
  9. static NSString *const PUTONGHUA = @"mandarin";  
  10. static NSString *const YUEYU     = @"cantonese";  
  11. static NSString *const HENANHUA  = @"henanese";  
  12. static NSString *const ENGLISH   = @"en_us";  
  13. static NSString *const CHINESE   = @"zh_cn";  
  14.   
  15. @implementation IATConfig  
  16.   
  17. - (id)init  
  18. {  
  19.     self  = [super init];  
  20.     if (self)  
  21.     {  
  22.         [self defaultSetting];  
  23.         return  self;  
  24.     }  
  25.     return nil;  
  26. }  
  27.   
  28. + (IATConfig *)sharedInstance  
  29. {  
  30.     static IATConfig  * instance = nil;  
  31.     static dispatch_once_t predict;  
  32.     dispatch_once(&predict, ^{  
  33.         instance = [[IATConfig alloc] init];  
  34.     });  
  35.     return instance;  
  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 = [[NSArray alloc] initWithObjects:@"粤语", @"普通话", @"河南话", @"英文", nil];  
  49. }  
  50.   
  51. + (NSString *)mandarin  
  52. {  
  53.     return PUTONGHUA;  
  54. }  
  55.   
  56. + (NSString *)cantonese  
  57. {  
  58.     return YUEYU;  
  59. }  
  60.   
  61. + (NSString *)henanese  
  62. {  
  63.     return HENANHUA;  
  64. }  
  65.   
  66. + (NSString *)chinese  
  67. {  
  68.     return CHINESE;  
  69. }  
  70.   
  71. + (NSString *)english  
  72. {  
  73.     return ENGLISH;  
  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. #pragma mark - 语音听写类  
  101.   
  102. static NSString *const VoiceAPPID   = @"572016e4";  
  103. static NSString *const VoiceTimeOut = @"20000";  
  104.   
  105. @interface VoiceConversion () <IFlySpeechRecognizerDelegate>  
  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)(BOOL isSuccess);  
  113. @property (nonatomic, copy) void (^resultSpeech)(NSString *text);  
  114. @property (nonatomic, copy) void (^volumeSpeech)(int volume);  
  115.   
  116. @end  
  117.   
  118. @implementation VoiceConversion  
  119.  
  120. #pragma mark 初始化------------  
  121.   
  122. /// 启动初始化语音程序  
  123. + (void)VoiceInitialize  
  124. {  
  125.     // 设置sdk的log等级,log保存在下面设置的工作路径中  
  126.     [IFlySetting setLogFile:LVL_ALL];  
  127.       
  128.     // 打开输出在console的log开关  
  129.     [IFlySetting showLogcat:YES];  
  130.       
  131.     // 设置sdk的工作路径  
  132.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
  133.     NSString *cachePath = [paths objectAtIndex:0];  
  134.     [IFlySetting setLogFilePath:cachePath];  
  135.       
  136.     // Appid是应用的身份信息,具有唯一性,初始化时必须要传入Appid。初始化是一个异步过程,可放在 App 启动时执行初始化,具体代码可以参 照 Demo 的 MSCAppDelegate.m。未初始化时使用服务,一般会返回错误码 10111.  
  137.     NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@", VoiceAPPID];  
  138.     [IFlySpeechUtility createUtility:initString];  
  139. }  
  140.  
  141. #pragma mark 实例化------------  
  142.   
  143. - (void)dealloc  
  144. {  
  145.     [self voiceCancel];  
  146. }  
  147.   
  148. - (NSMutableString *)resultText  
  149. {  
  150.     if (!_resultText)  
  151.     {  
  152.         _resultText = [[NSMutableString alloc] init];  
  153.     }  
  154.       
  155.     return _resultText;  
  156. }  
  157.   
  158. - (IFlySpeechRecognizer *)iFlySpeechRecognizer  
  159. {  
  160.     if (_iFlySpeechRecognizer == nil)  
  161.     {  
  162.         _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];  
  163.           
  164.         [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];  
  165.         // 设置听写模式  
  166.         [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];  
  167.     }  
  168.       
  169.     return _iFlySpeechRecognizer;  
  170. }  
  171.   
  172. - (void)initializeVoice  
  173. {  
  174.     self.iFlySpeechRecognizer.delegate = self;  
  175.   
  176.     IATConfig *instance = [IATConfig sharedInstance];  
  177.           
  178.     // 设置最长录音时间  
  179.     [self.iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];  
  180.     // 设置后端点  
  181.     [self.iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];  
  182.     // 设置前端  
  183.     [self.iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];  
  184.     // 网络等待时间  
  185.     [self.iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];  
  186.       
  187.     // 设置采样率,推荐使用16K  
  188.     [self.iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];  
  189.       
  190.     if ([instance.language isEqualToString:[IATConfig chinese]])  
  191.     {  
  192.         // 设置语言  
  193.         [self.iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];  
  194.         // 设置方言  
  195.         [self.iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];  
  196.     }  
  197.     else if ([instance.language isEqualToString:[IATConfig english]])  
  198.     {  
  199.         [self.iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];  
  200.     }  
  201.       
  202.     // 设置是否返回标点符号  
  203.     [self.iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];  
  204. }  
  205.  
  206. #pragma mark 语音听写方法------------  
  207.   
  208. /// 开始录音  
  209. - (void)voiceStart:(void (^)(BOOL isStart))startListening   
  210.        speechBegin:(void (^)(void))begin   
  211.          speechEnd:(void (^)(void))end   
  212.        speechError:(void (^)(BOOL isSuccess))error   
  213.       speechResult:(void (^)(NSString *text))result   
  214.       speechVolume:(void (^)(int volume))volume  
  215. {  
  216.     [self.resultText setString:@""];  
  217.       
  218.     // 回调设置  
  219.     self.beginSpeech = [begin copy];  
  220.     self.endSpeech = [end copy];  
  221.     self.errorSpeech = [error copy];  
  222.     self.resultSpeech = [result copy];  
  223.     self.volumeSpeech = [volume copy];  
  224.       
  225.       
  226.     // 初始化设置  
  227.     [self initializeVoice];  
  228.       
  229.     [self.iFlySpeechRecognizer cancel];  
  230.       
  231.     // 设置音频来源为麦克风  
  232.     [self.iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];  
  233.       
  234.     // 设置听写结果格式为json  
  235.     [self.iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];  
  236.       
  237.     // 保存录音文件,保存在sdk工作路径中,如未设置工作路径,则默认保存在library/cache下  
  238.     [self.iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];  
  239.       
  240.     BOOL isStart = [self.iFlySpeechRecognizer startListening];  
  241.     if (startListening)  
  242.     {  
  243.         // 如果开始录音失败,可能是上次请求未结束,暂不支持多路并发  
  244.         startListening(isStart);  
  245.     }  
  246. }  
  247.   
  248. /// 取消听写  
  249. - (void)voiceCancel  
  250. {  
  251.     [self.iFlySpeechRecognizer cancel];  
  252. }  
  253.   
  254. /// 停止录音  
  255. - (void)voiceStop  
  256. {  
  257.     [self.iFlySpeechRecognizer stopListening];  
  258. }  
  259.  
  260. #pragma mark IFlySpeechRecognizerDelegate------------  
  261.   
  262. /** 
  263.  识别结果返回代理 
  264.  @param :results识别结果 
  265.  @ param :isLast 表示是否最后一次结果 
  266.  */  
  267. - (void)onResults:(NSArray *)results isLast:(BOOL)isLast  
  268. {  
  269.     NSMutableString *resultString = [[NSMutableString alloc] init];  
  270.     NSDictionary *dic = results[0];  
  271.     for (NSString *key in dic)  
  272.     {  
  273.         [resultString appendFormat:@"%@",key];  
  274.     }  
  275.     NSString *resultFromJson = [[self class] stringFromJson:resultString];  
  276.     NSString *resultTextTemp = [NSString stringWithFormat:@"%@%@", self.resultText, resultFromJson];  
  277.     [self.resultText setString:resultTextTemp];  
  278.     if (isLast)  
  279.     {  
  280.         if (self.resultSpeech)  
  281.         {  
  282.             // 去掉最后一个句号  
  283.             NSRange range = [self.resultText rangeOfString:@"。" options:NSBackwardsSearch];  
  284.             if (range.location != NSNotFound)  
  285.             {  
  286.                 resultTextTemp = [self.resultText substringToIndex:range.location];  
  287.                 [self.resultText setString:resultTextTemp];  
  288.             }  
  289.             self.resultSpeech(self.resultText);  
  290.         }  
  291.     }  
  292.       
  293.     [self voiceCancel];  
  294. }  
  295.   
  296. /** 
  297.  识别会话结束返回代理 
  298.  @ param error 错误码,error.errorCode=0表示正常结束,非0表示发生错误。  
  299.  */  
  300. - (void)onError:(IFlySpeechError *)error  
  301. {  
  302.     if (self.errorSpeech)  
  303.     {  
  304.         BOOL isSuccess = (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.  音量回调函数 volume 0-30 
  333.  */  
  334. - (void)onVolumeChanged:(int)volume  
  335. {  
  336.     if (self.volumeSpeech)  
  337.     {  
  338.         self.volumeSpeech(volume);  
  339.     }  
  340. }  
  341.  
  342.  
  343. #pragma mark 解析方法------------  
  344.   
  345. /**************************************************************************/  
  346.   
  347. /** 
  348.  解析命令词返回的结果 
  349.  */  
  350. + (NSString *)stringFromAsr:(NSString *)params;  
  351. {  
  352.     NSMutableString * resultString = [[NSMutableString alloc] init];  
  353.     NSString *inputString = nil;  
  354.       
  355.     NSArray *array = [params componentsSeparatedByString:@"\n"];  
  356.       
  357.     for (int index = 0; index < array.count; index++)  
  358.     {  
  359.         NSRange range;  
  360.         NSString *line = [array objectAtIndex:index];  
  361.           
  362.         NSRange idRange = [line rangeOfString:@"id="];  
  363.         NSRange nameRange = [line rangeOfString:@"name="];  
  364.         NSRange confidenceRange = [line rangeOfString:@"confidence="];  
  365.         NSRange grammarRange = [line rangeOfString:@" grammar="];  
  366.           
  367.         NSRange inputRange = [line rangeOfString:@"input="];  
  368.           
  369.         if (confidenceRange.length == 0 || grammarRange.length == 0 || inputRange.length == 0 )  
  370.         {  
  371.             continue;  
  372.         }  
  373.           
  374.         // check nomatch  
  375.         if (idRange.length != 0)  
  376.         {  
  377.             NSUInteger idPosX = idRange.location + idRange.length;  
  378.             NSUInteger idLength = nameRange.location - idPosX;  
  379.             range = NSMakeRange(idPosX, idLength);  
  380.               
  381.             NSString *subString = [line substringWithRange:range];  
  382.             NSCharacterSet *subSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];  
  383.             NSString *idValue = [subString stringByTrimmingCharactersInSet:subSet];  
  384.             if ([idValue isEqualToString:@"nomatch"])  
  385.             {  
  386.                 return @"";  
  387.             }  
  388.         }  
  389.           
  390.         // Get Confidence Value  
  391.         NSUInteger confidencePosX = confidenceRange.location + confidenceRange.length;  
  392.         NSUInteger confidenceLength = grammarRange.location - confidencePosX;  
  393.         range = NSMakeRange(confidencePosX,confidenceLength);  
  394.           
  395.         NSString *score = [line substringWithRange:range];  
  396.           
  397.         NSUInteger inputStringPosX = inputRange.location + inputRange.length;  
  398.         NSUInteger inputStringLength = line.length - inputStringPosX;  
  399.           
  400.         range = NSMakeRange(inputStringPosX , inputStringLength);  
  401.         inputString = [line substringWithRange:range];  
  402.           
  403.         [resultString appendFormat:@"%@ 置信度%@\n",inputString, score];  
  404.     }  
  405.       
  406.     return resultString;  
  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.         return nil;  
  419.     }  
  420.       
  421.     NSMutableString *tempStr = [[NSMutableString alloc] init];  
  422.     // 返回的格式必须为utf8的,否则发生未知错误  
  423.     NSData *dataJSON = [params dataUsingEncoding:NSUTF8StringEncoding];  
  424.     NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:dataJSON options:kNilOptions error:nil];  
  425.       
  426.     if (resultDic != nil)  
  427.     {  
  428.         NSArray *wordArray = [resultDic objectForKey:@"ws"];  
  429.           
  430.         for (int i = 0; i < [wordArray count]; i++)  
  431.         {  
  432.             NSDictionary *wsDic = [wordArray objectAtIndex:i];  
  433.             NSArray *cwArray = [wsDic objectForKey:@"cw"];  
  434.               
  435.             for (int j = 0; j < [cwArray count]; j++)  
  436.             {  
  437.                 NSDictionary *wDic = [cwArray objectAtIndex:j];  
  438.                 NSString *str = [wDic objectForKey:@"w"];  
  439.                 [tempStr appendString: str];  
  440.             }  
  441.         }  
  442.     }  
  443.       
  444.     return tempStr;  
  445. }  
  446.   
  447.   
  448. /** 
  449.  解析语法识别返回的结果 
  450.  */  
  451. + (NSString *)stringFromABNFJson:(NSString *)params  
  452. {  
  453.     if (params == NULL)  
  454.     {  
  455.         return nil;  
  456.     }  
  457.     NSMutableString *tempStr = [[NSMutableString alloc] init];  
  458.     NSData *dataJSON = [params dataUsingEncoding:NSUTF8StringEncoding];  
  459.     NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:dataJSON options:kNilOptions error:nil];  
  460.       
  461.     NSArray *wordArray = [resultDic objectForKey:@"ws"];  
  462.     for (int i = 0; i < [wordArray count]; i++)  
  463.     {  
  464.         NSDictionary *wsDic = [wordArray objectAtIndex:i];  
  465.         NSArray *cwArray = [wsDic objectForKey:@"cw"];  
  466.           
  467.         for (int j = 0; j < [cwArray count]; j++)  
  468.         {  
  469.             NSDictionary *wDic = [cwArray objectAtIndex:j];  
  470.             NSString *str = [wDic objectForKey:@"w"];  
  471.             NSString *score = [wDic objectForKey:@"sc"];  
  472.             [tempStr appendString: str];  
  473.             [tempStr appendFormat:@" 置信度:%@",score];  
  474.             [tempStr appendString: @"\n"];  
  475.         }  
  476.     }  
  477.       
  478.     return tempStr;  
  479. }  
  480.   
  481. /**************************************************************************/  
  482.   
  483. @end  


使用

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 初始化方法  
  2. /// 启动初始化语音程序  
  3. + (void)VoiceInitialize  
  4. {  
  5.     // 设置sdk的log等级,log保存在下面设置的工作路径中  
  6.     [IFlySetting setLogFile:LVL_ALL];  
  7.       
  8.     // 打开输出在console的log开关  
  9.     [IFlySetting showLogcat:YES];  
  10.       
  11.     // 设置sdk的工作路径  
  12.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
  13.     NSString *cachePath = [paths objectAtIndex:0];  
  14.     [IFlySetting setLogFilePath:cachePath];  
  15.       
  16.     // Appid是应用的身份信息,具有唯一性,初始化时必须要传入Appid。初始化是一个异步过程,可放在 App 启动时执行初始化,具体代码可以参 照 Demo 的 MSCAppDelegate.m。未初始化时使用服务,一般会返回错误码 10111.  
  17.     NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@", VoiceAPPID];  
  18.     [IFlySpeechUtility createUtility:initString];  
  19. }  
  20.   
  21. 初始化调用  
  22. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions   
  23. {  
  24.     // Override point for customization after application launch.  
  25.       
  26.     [VoiceConversion VoiceInitialize];  
  27.       
  28.     return YES;  
  29. }  


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #import "VoiceConversion.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @property (nonatomicstrongVoiceConversion *voiceConversion;  
  6. @property (nonatomicstrongUILabel *messageLabel;  
  7.   
  8. @end  
  9.   
  10. @implementation ViewController  
  11.   
  12. - (void)viewDidLoad {  
  13.     [super viewDidLoad];  
  14.     // Do any additional setup after loading the view, typically from a nib.  
  15.       
  16.     UIBarButtonItem *startItem = [[UIBarButtonItem alloc] initWithTitle:@"start" style:UIBarButtonItemStyleDone target:self action:@selector(startItemClick:)];  
  17.     UIBarButtonItem *stopItem = [[UIBarButtonItem alloc] initWithTitle:@"stop" style:UIBarButtonItemStyleDone target:self action:@selector(stopItemClick:)];  
  18.     UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"cancel" style:UIBarButtonItemStyleDone target:self action:@selector(cancelItemClick:)];  
  19.     self.navigationItem.rightBarButtonItems = @[startItem, stopItem, cancelItem];  
  20.       
  21.     self.title = @"科大讯飞语音";  
  22.       
  23.     [self setUI];  
  24. }  
  25.   
  26. - (void)didReceiveMemoryWarning {  
  27.     [super didReceiveMemoryWarning];  
  28.     // Dispose of any resources that can be recreated.  
  29. }  
  30.   
  31. #pragma mark - 视图  
  32.   
  33. - (void)setUI  
  34. {  
  35.     if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])  
  36.     {  
  37.         [self setEdgesForExtendedLayout:UIRectEdgeNone];  
  38.     }  
  39.       
  40.     self.messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.010.0, CGRectGetWidth(self.view.bounds) - 10.0 * 240.0)];  
  41.     [self.view addSubview:self.messageLabel];  
  42.     self.messageLabel.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.3];  
  43.     self.messageLabel.textAlignment = NSTextAlignmentCenter;  
  44. }  
  45.   
  46. #pragma mark - 响应  
  47.   
  48. - (void)startItemClick:(UIBarButtonItem *)item  
  49. {  
  50.     ViewController __weak *weakSelf = self;  
  51.     [self.voiceConversion voiceStart:^(BOOL isStart) {  
  52.           
  53.         NSLog(@"1 start");  
  54.           
  55.         if (isStart)  
  56.         {  
  57.             weakSelf.messageLabel.text = @"正在录音";  
  58.         }  
  59.         else  
  60.         {  
  61.             weakSelf.messageLabel.text = @"启动识别服务失败,请稍后重试";  
  62.         }  
  63.     } speechBegin:^{  
  64.         NSLog(@"2 begin");  
  65.     } speechEnd:^{  
  66.         NSLog(@"3 end");  
  67.     } speechError:^(BOOL isSuccess) {  
  68.         NSLog(@"4 error");  
  69.     } speechResult:^(NSString *text) {  
  70.         NSLog(@"5 result");  
  71.         weakSelf.messageLabel.text = text;  
  72.     } speechVolume:^(int volume) {  
  73.         NSLog(@"6 volume");  
  74.         NSString *volumeString = [NSString stringWithFormat:@"音量:%d", volume];  
  75.         weakSelf.messageLabel.text = volumeString;  
  76.     }];  
  77. }  
  78.   
  79. - (void)stopItemClick:(UIBarButtonItem *)item  
  80. {  
  81.     [self.voiceConversion voiceStop];  
  82.       
  83.     self.messageLabel.text = @"停止录音";  
  84. }  
  85.   
  86. - (void)cancelItemClick:(UIBarButtonItem *)item  
  87. {  
  88.     [self.voiceConversion voiceCancel];  
  89.       
  90.     self.messageLabel.text = @"取消识别";  
  91. }  
  92.   
  93. #pragma mark - getter  
  94.   
  95. - (VoiceConversion *)voiceConversion  
  96. {  
  97.     if (!_voiceConversion)  
  98.     {  
  99.         _voiceConversion = [[VoiceConversion alloc] init];  
  100.     }  
  101.       
  102.     return _voiceConversion;  
  103. }  
  104.   
  105. @end  





Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐