最近需要做一个语言搜索的功能,所以需要用到语言识别的SDK,最终选择科大讯飞的SDK.
科大讯飞APPkey的获取直接申请应用就可以了
集成SDK主要参考官方文档:http://doc.xfyun.cn/msc_ios/302721,基本不会有问题
下面主要是记录代码部分:
1.首先需要在appdelegate的didFinishLaunchingWithOptions方法中启用讯飞的SDK
2.新建一个类,初始化IFlySpeechRecognizer
3.sdk识别出来的是一串json字符串,所以还需要一个方法将字符串里的字符提取出来
```/**
解析听写json格式的数据
params例如:
{"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}]}]}
*/
-(NSString*)getResultFromJson:(NSString*)params
{
if(params ==NULL) {
returnnil;
}
NSString *tempStr = [[NSString alloc] init];
//返回的格式必须为utf8的,否则发生未知错误
NSString*jsonString = params;
tempStr = [selfVoiceConversionString:jsonString];
returntempStr;
}
- (NSString*)VoiceConversionString:(NSString*)jsonString{
NSDictionary*values = [JKJsonHelpertoJsonObject:jsonString];
NSMutableString *discourse = [NSMutableString string];
NSArray*ws = [valuesobjectForKey:@"ws"];
for(NSDictionary*dicinws) {
NSArray*cw = [dicobjectForKey:@"cw"];
for(NSDictionary*secDicincw) {
NSString*w = [secDicobjectForKey:@"w"];
[discourseappendString:w];
}
} returndiscourse;
}```
4.在需要的view里调用创建这个类并设置delegate
```
self.voiceSearchMVVM = [JKVoiceSearchMVVM create];
_voiceRecognition = [NSString string]; // 保存识别的字符串
[self.loading setupAlpha:0.8];
self.voiceSearchMVVM.iflySpeechRecognizer.delegate = self;
```
5.开启语音识别
```
bool ret = [self.voiceSearchMVVM.iflySpeechRecognizer startListening];
if(ret) {
// 开启成功
self.wavesView.hidden=NO;
[self.waveViewwave];
}
else
{
self.wavesView.hidden=YES;
// 开启失败
[self showToast:@"启动识别服务失败,请稍后重试"];
}
```
6.停止语音识别
```
if (self.voiceSearchMVVM.iflySpeechRecognizer.isListening) {
[self.voiceSearchMVVM.iflySpeechRecognizer stopListening];
}
```
7.取消语音识别
```
[self.voiceSearchMVVM.iflySpeechRecognizer cancel];
```
8.实现代理
- (void)onBeginOfSpeech
{
DDLogDebug(@"开始语音识别");
}
- (void)onVolumeChanged:(int)volume{
// 语音声音大小
}
- (void)onResults:(NSArray*)results isLast:(BOOL)isLast{
// 语音结果识别后回调,因为语音识别是一段段识别,所以应保存所有识别的语句,当isLast为yes时才算识别完成
if(results)
{
NSMutableString *resultString = [[NSMutableString alloc] init];
NSDictionary*dic = results[0];
for(NSString*keyindic)
{
[resultStringappendFormat:@"%@",key];
}
NSString* resultFromJson = [self.voiceSearchMVVMgetResultFromJson:resultString];
_voiceRecognition = [_voiceRecognition stringByAppendingString:resultFromJson];
}
if(isLast)
{
if (_voiceRecognition.length>0) {
int64_tdelayInSeconds =1.0; // 延迟的时间
dispatch_time_tpopTime =dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// 识别成功
});
}else{
int64_tdelayInSeconds =1.0; // 延迟的时间
dispatch_time_tpopTime =dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// 识别失败
});
}
}
DDLogDebug(@"isLast=%d",isLast);
}