下面是详细讲解“为textView添加语音输入功能的实例代码(集成讯飞语音识别)”的完整攻略。
步骤一:添加讯飞语音识别SDK
首先,你需要先下载并添加讯飞语音识别SDK到你的工程中。你可以进入讯飞官网,注册一个账号,然后下载需要的SDK。添加SDK的方式有两种:
1.使用CocoaPods
在你的工程目录下添加Podfile文件,内容如下:
platform :ios,'10.0'
#注意:因为本例引入了AFNetworking,需要在podfile文件里额外添加关于AFNetworking的声明
inhibit_all_warnings!
target 'Your Target' do
pod 'MSCoreTextView'
pod 'IFlyMSC'
end
你需要将Your Target
替换成你的工程target的名称。然后,在终端中执行以下命令:
pod install
2.手动添加SDK
将你下载的SDK文件夹拖入你的工程中。如果使用手动添加SDK,你需要在你的工程属性下的Build Settings
里找到Header Search Paths
选项,在其值中添加SDK的头文件目录,例如:${PROJECT_DIR}/YourSDKFolder/headers/
。
步骤二:添加头文件
在需要使用语音输入功能的文件中添加以下头文件:
#import <IFlyMSC/IFlyMSC.h>
#import <IFlySpeechRecognizerDelegate.h>
#import <IFlySpeechRecognizer.h>
#import <IFlySpeechConstant.h>
步骤三:初始化语音识别对象
在你需要使用语音识别功能的时候,你需要初始化一个IFlySpeechRecognizer
对象,如下所示:
IFlySpeechRecognizer *_iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
_iFlySpeechRecognizer.delegate = self;
[_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
[_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
//设置是否返回标点符号,默认为NO
[_iFlySpeechRecognizer setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT]];
注意:IFlySpeechRecognizerDelegate
是语音识别回调的代理对象。
步骤四:在textView中添加语音输入功能
在textView中添加语音输入功能的实现,有多种方式可以选择,这里提供一种常用的方式:
//textView初始化之后,设置它的inputView为语音识别的输入视图
- (void)viewDidLoad {
[super viewDidLoad];
self.textView.inputView = [self addVoiceInputView];
}
//添加语音识别输入视图
-(UIView *)addVoiceInputView{
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_WIDTH, 40)];
view.backgroundColor = [UIColor lightGrayColor];
UIButton *voiceButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 5, 30, 30)];
[voiceButton setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
[voiceButton addTarget:self action:@selector(tapVoiceButton:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:voiceButton];
return view;
}
//点击语音输入按钮
-(void)tapVoiceButton:(id)sender {
[self.textView resignFirstResponder];
[_iFlySpeechRecognizer startListening];
}
在上述代码中,我们将textView的inputView设置为一个UIView,然后在这个UIView中添加了一个语音输入按钮。当点击语音输入按钮时,我们调用startListening
方法开始语音识别。
步骤五:实现IFlySpeechRecognizerDelegate回调方法
当语音识别开始或结束时,IFlySpeechRecognizerDelegate
协议的代理方法会被调用。你可以在这些方法中实现语音识别的逻辑。以下代码是一个简单的实现,用于将识别结果显示在textView 中:
#pragma mark - IFlySpeechRecognizerDelegate
//结果返回代理
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast {
NSMutableString *result = [[NSMutableString alloc]init];
NSDictionary *dic = resultArray[0];
for (NSString *key in dic) {
[result appendFormat:@"%@",key];
}
NSString * resultFromJson = [self stringFromJson:result];
resultFromJson = [resultFromJson stringByReplacingOccurrencesOfString:@"。" withString:@""];
// NSLog(@"%@",resultFromJson);
self.textView.text = [NSString stringWithFormat:@"%@%@",self.textView.text,resultFromJson];
}
//识别结束回调
-(void)onError:(IFlySpeechError *)errorCode{
NSLog(@"%s",__func__);
}
//停止录音回调
- (void)onEndOfSpeech{
NSLog(@"停止录音");
}
//开始录音回调
- (void)onBeginOfSpeech{
NSLog(@"开始录音");
}
#pragma mark - json解析
- (NSString *)stringFromJson:(NSString *)params
{
NSData * data = [params dataUsingEncoding:NSUTF8StringEncoding];
NSError * error;
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
if(error) {
NSLog(@"json解析失败:%@",error);
return nil;
}
NSLog(@"%@",dic);
return [dic objectForKey:@"content"];
}
在上述代码中,我们实现了IFlySpeechRecognizerDelegate
协议的代理方法,对结果进行处理,并用NSJSONSerialization
将结果转化成NSString类型。
示例一:将语音输入结果保存到本地
我们可以将语音结果保存到本地,使得用户在下次编辑时可以方便地进行编辑。
#pragma mark - IFlySpeechRecognizerDelegate
//结果返回代理
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast {
NSMutableString *result = [[NSMutableString alloc]init];
NSDictionary *dic = resultArray[0];
for (NSString *key in dic) {
[result appendFormat:@"%@",key];
}
NSString * resultFromJson = [self stringFromJson:result];
resultFromJson = [resultFromJson stringByReplacingOccurrencesOfString:@"。" withString:@""];
NSLog(@"%@",resultFromJson);
//将语音识别结果保存到本地
NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentDirectory stringByAppendingPathComponent:@"voiceResult.txt"];
NSString *resultString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
if (!resultString) {
resultString = @"";
}
NSString *newResultString = [NSString stringWithFormat:@"%@\n%@",resultString,resultFromJson];
[newResultString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
self.textView.text = [NSString stringWithFormat:@"%@%@",self.textView.text,resultFromJson];
}
示例二:语音输入和键盘输入进行切换
我们可以添加一个切换按钮,在语音输入和键盘输入之间进行切换。
//添加语音识别输入视图
-(UIView *)addVoiceInputView{
self.voiceInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_WIDTH, 40)];
self.voiceInputView.backgroundColor = [UIColor lightGrayColor];
UIButton *voiceButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 5, 30, 30)];
[voiceButton setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
[voiceButton addTarget:self action:@selector(tapVoiceButton:) forControlEvents:UIControlEventTouchUpInside];
[self.voiceInputView addSubview:voiceButton];
UIButton *keyboardButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreen_WIDTH - 40, 5, 30, 30)];
[keyboardButton setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
[keyboardButton addTarget:self action:@selector(tapKeyboardButton:) forControlEvents:UIControlEventTouchUpInside];
[self.voiceInputView addSubview:keyboardButton];
return self.voiceInputView;
}
//点击语音输入按钮
-(void)tapVoiceButton:(id)sender {
[self.textView resignFirstResponder];
_isVoiceInput = YES;
[_iFlySpeechRecognizer startListening];
}
//点击键盘输入按钮
-(void)tapKeyboardButton:(id)sender {
[self.textView becomeFirstResponder];
_isVoiceInput = NO;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (_isVoiceInput) {
return NO;
}
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
在上述代码中,我们在语音输入视图中添加了一个切换按钮keyboardButton
。当语音输入结束时,我们将_isVoiceInput
变量设置为YES,然后在UITextFieldDelegate代理方法中返回NO,禁用键盘输入;当点击切换按钮时,调用tapKeyboardButton
方法切换到键盘输入,这时候再将_isVoiceInput
变量值设为NO,以启用键盘输入。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:为textView添加语音输入功能的实例代码(集成讯飞语音识别) - Python技术站