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、在使用前,务必在AppDelegate的方法中"

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

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


如图

下载的科大讯飞SDK文件


Demo中的APPID


添加SDK


添加关联framework




语音转文件实现代码

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:14px;">.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 (nonatomicstrongNSString *speechTimeout;  
  34. @property (nonatomicstrongNSString *vadEos;  
  35. @property (nonatomicstrongNSString *vadBos;  
  36.   
  37. @property (nonatomicstrongNSString *language;  
  38. @property (nonatomicstrongNSString *accent;  
  39.   
  40. @property (nonatomicstrongNSString *dot;  
  41. @property (nonatomicstrongNSString *sampleRate;  
  42.   
  43.   
  44. /** 
  45.  以下参数无需设置 不必关 
  46.  */  
  47. @property (nonatomic, assign) BOOL haveView;  
  48. @property (nonatomicstrongNSArray *accentIdentifer;  
  49. @property (nonatomicstrongNSArray *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 speechBegin:(void (^)(void))begin speechEnd:(void (^)(void))end speechError:(void (^)(BOOL isSuccess))error speechResult:(void (^)(NSString *text))result speechVolume:(void (^)(int volume))volume;  
  66.   
  67. /// 取消录音  
  68. - (void)voiceCancel;  
  69.   
  70. /// 停止录音  
  71. - (void)voiceStop;  
  72.   
  73. @end  
  74. </span>  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:14px;">.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 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 (nonatomicstrongNSMutableString *resultText;  
  108. @property (nonatomicstrongIFlySpeechRecognizer *iFlySpeechRecognizer;  
  109.   
  110. @property (nonatomiccopyvoid (^beginSpeech)(void);  
  111. @property (nonatomiccopyvoid (^endSpeech)(void);  
  112. @property (nonatomiccopyvoid (^errorSpeech)(BOOL isSuccess);  
  113. @property (nonatomiccopyvoid (^resultSpeech)(NSString *text);  
  114. @property (nonatomiccopyvoid (^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 speechBegin:(void (^)(void))begin speechEnd:(void (^)(void))end speechError:(void (^)(BOOL isSuccess))error speechResult:(void (^)(NSString *text))result speechVolume:(void (^)(int volume))volume  
  210. {  
  211.     [self.resultText setString:@""];  
  212.       
  213.     // 回调设置  
  214.     self.beginSpeech = [begin copy];  
  215.     self.endSpeech = [end copy];  
  216.     self.errorSpeech = [error copy];  
  217.     self.resultSpeech = [result copy];  
  218.     self.volumeSpeech = [volume copy];  
  219.       
  220.       
  221.     // 初始化设置  
  222.     [self initializeVoice];  
  223.       
  224.     [self.iFlySpeechRecognizer cancel];  
  225.       
  226.     // 设置音频来源为麦克风  
  227.     [self.iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];  
  228.       
  229.     // 设置听写结果格式为json  
  230.     [self.iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];  
  231.       
  232.     // 保存录音文件,保存在sdk工作路径中,如未设置工作路径,则默认保存在library/cache下  
  233.     [self.iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];  
  234.       
  235.     BOOL isStart = [self.iFlySpeechRecognizer startListening];  
  236.     if (startListening)  
  237.     {  
  238.         // 如果开始录音失败,可能是上次请求未结束,暂不支持多路并发  
  239.         startListening(isStart);  
  240.     }  
  241. }  
  242.   
  243. /// 取消听写  
  244. - (void)voiceCancel  
  245. {  
  246.     [self.iFlySpeechRecognizer cancel];  
  247. }  
  248.   
  249. /// 停止录音  
  250. - (void)voiceStop  
  251. {  
  252.     [self.iFlySpeechRecognizer stopListening];  
  253. }  
  254.   
  255. #pragma mark IFlySpeechRecognizerDelegate------------  
  256.   
  257. /** 
  258.  识别结果返回代理 
  259.  @param :results识别结果 
  260.  @ param :isLast 表示是否最后一次结果 
  261.  */  
  262. - (void)onResults:(NSArray *)results isLast:(BOOL)isLast  
  263. {  
  264.     NSMutableString *resultString = [[NSMutableString alloc] init];  
  265.     NSDictionary *dic = results[0];  
  266.     for (NSString *key in dic)  
  267.     {  
  268.         [resultString appendFormat:@"%@",key];  
  269.     }  
  270.     NSString *resultFromJson =  [[self class] stringFromJson:resultString];  
  271.     NSString *resultTextTemp = [NSString stringWithFormat:@"%@%@"self.resultText, resultFromJson];  
  272.     [self.resultText setString:resultTextTemp];  
  273.     if (self.resultSpeech)  
  274.     {  
  275.         self.resultSpeech(self.resultText);  
  276.     }  
  277. }  
  278.   
  279. /** 
  280.  识别会话结束返回代理 
  281.  @ param error 错误码,error.errorCode=0表示正常结束,非0表示发生错误。  
  282.  */  
  283. - (void)onError:(IFlySpeechError *)error  
  284. {  
  285.     if (self.errorSpeech)  
  286.     {  
  287.         BOOL isSuccess = (0 == error.errorCode);  
  288.         self.errorSpeech(isSuccess);  
  289.     }  
  290. }  
  291.   
  292. /** 
  293.  停止录音回调 
  294.  */  
  295. - (void)onEndOfSpeech  
  296. {  
  297.     if (self.endSpeech)  
  298.     {  
  299.         self.endSpeech();  
  300.     }  
  301. }  
  302.   
  303. /** 
  304.  开始识别回调 
  305.  */  
  306. - (void)onBeginOfSpeech  
  307. {  
  308.     if (self.beginSpeech)  
  309.     {  
  310.         self.beginSpeech();  
  311.     }  
  312. }  
  313.   
  314. /** 
  315.  音量回调函数 volume 0-30 
  316.  */  
  317. - (void)onVolumeChanged:(int)volume  
  318. {  
  319.     if (self.volumeSpeech)  
  320.     {  
  321.         self.volumeSpeech(volume);  
  322.     }  
  323. }  
  324.   
  325.   
  326. #pragma mark 解析方法------------  
  327.   
  328. /**************************************************************************/  
  329.   
  330. /** 
  331.  解析命令词返回的结果 
  332.  */  
  333. + (NSString *)stringFromAsr:(NSString *)params;  
  334. {  
  335.     NSMutableString * resultString = [[NSMutableString alloc] init];  
  336.     NSString *inputString = nil;  
  337.       
  338.     NSArray *array = [params componentsSeparatedByString:@"\n"];  
  339.       
  340.     for (int index = 0; index < array.count; index++)  
  341.     {  
  342.         NSRange range;  
  343.         NSString *line = [array objectAtIndex:index];  
  344.           
  345.         NSRange idRange = [line rangeOfString:@"id="];  
  346.         NSRange nameRange = [line rangeOfString:@"name="];  
  347.         NSRange confidenceRange = [line rangeOfString:@"confidence="];  
  348.         NSRange grammarRange = [line rangeOfString:@" grammar="];  
  349.           
  350.         NSRange inputRange = [line rangeOfString:@"input="];  
  351.           
  352.         if (confidenceRange.length == 0 || grammarRange.length == 0 || inputRange.length == 0 )  
  353.         {  
  354.             continue;  
  355.         }  
  356.           
  357.         // check nomatch  
  358.         if (idRange.length != 0)  
  359.         {  
  360.             NSUInteger idPosX = idRange.location + idRange.length;  
  361.             NSUInteger idLength = nameRange.location - idPosX;  
  362.             range = NSMakeRange(idPosX, idLength);  
  363.               
  364.             NSString *subString = [line substringWithRange:range];  
  365.             NSCharacterSet *subSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];  
  366.             NSString *idValue = [subString stringByTrimmingCharactersInSet:subSet];  
  367.             if ([idValue isEqualToString:@"nomatch"])  
  368.             {  
  369.                 return @"";  
  370.             }  
  371.         }  
  372.           
  373.         // Get Confidence Value  
  374.         NSUInteger confidencePosX = confidenceRange.location + confidenceRange.length;  
  375.         NSUInteger confidenceLength = grammarRange.location - confidencePosX;  
  376.         range = NSMakeRange(confidencePosX,confidenceLength);  
  377.           
  378.         NSString *score = [line substringWithRange:range];  
  379.           
  380.         NSUInteger inputStringPosX = inputRange.location + inputRange.length;  
  381.         NSUInteger inputStringLength = line.length - inputStringPosX;  
  382.           
  383.         range = NSMakeRange(inputStringPosX , inputStringLength);  
  384.         inputString = [line substringWithRange:range];  
  385.           
  386.         [resultString appendFormat:@"%@ 置信度%@\n",inputString, score];  
  387.     }  
  388.       
  389.     return resultString;  
  390. }  
  391.   
  392. /** 
  393.  解析听写json格式的数据 
  394.  params例如: 
  395.  {"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}]}]} 
  396.  */  
  397. + (NSString *)stringFromJson:(NSString *)params  
  398. {  
  399.     if (params == NULL)  
  400.     {  
  401.         return nil;  
  402.     }  
  403.       
  404.     NSMutableString *tempStr = [[NSMutableString alloc] init];  
  405.     // 返回的格式必须为utf8的,否则发生未知错误  
  406.     NSData *dataJSON = [params dataUsingEncoding:NSUTF8StringEncoding];  
  407.     NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:dataJSON options:kNilOptions error:nil];  
  408.       
  409.     if (resultDic != nil)  
  410.     {  
  411.         NSArray *wordArray = [resultDic objectForKey:@"ws"];  
  412.           
  413.         for (int i = 0; i < [wordArray count]; i++)  
  414.         {  
  415.             NSDictionary *wsDic = [wordArray objectAtIndex:i];  
  416.             NSArray *cwArray = [wsDic objectForKey:@"cw"];  
  417.               
  418.             for (int j = 0; j < [cwArray count]; j++)  
  419.             {  
  420.                 NSDictionary *wDic = [cwArray objectAtIndex:j];  
  421.                 NSString *str = [wDic objectForKey:@"w"];  
  422.                 [tempStr appendString: str];  
  423.             }  
  424.         }  
  425.     }  
  426.       
  427.     return tempStr;  
  428. }  
  429.   
  430.   
  431. /** 
  432.  解析语法识别返回的结果 
  433.  */  
  434. + (NSString *)stringFromABNFJson:(NSString *)params  
  435. {  
  436.     if (params == NULL)  
  437.     {  
  438.         return nil;  
  439.     }  
  440.     NSMutableString *tempStr = [[NSMutableString alloc] init];  
  441.     NSData *dataJSON = [params dataUsingEncoding:NSUTF8StringEncoding];  
  442.     NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:dataJSON options:kNilOptions error:nil];  
  443.       
  444.     NSArray *wordArray = [resultDic objectForKey:@"ws"];  
  445.     for (int i = 0; i < [wordArray count]; i++)  
  446.     {  
  447.         NSDictionary *wsDic = [wordArray objectAtIndex:i];  
  448.         NSArray *cwArray = [wsDic objectForKey:@"cw"];  
  449.           
  450.         for (int j = 0; j < [cwArray count]; j++)  
  451.         {  
  452.             NSDictionary *wDic = [cwArray objectAtIndex:j];  
  453.             NSString *str = [wDic objectForKey:@"w"];  
  454.             NSString *score = [wDic objectForKey:@"sc"];  
  455.             [tempStr appendString: str];  
  456.             [tempStr appendFormat:@" 置信度:%@",score];  
  457.             [tempStr appendString@"\n"];  
  458.         }  
  459.     }  
  460.       
  461.     return tempStr;  
  462. }  
  463.   
  464. /**************************************************************************/  
  465.   
  466. @end  
  467. </span>  


使用

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:14px;">初始化方法  
  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. }</span>  


[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:14px;">#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  
  106. </span>  






1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值