为textView添加语音输入功能的实例代码(集成讯飞语音识别)

yizhihongxing

下面是详细讲解“为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技术站

(0)
上一篇 2023年6月26日
下一篇 2023年6月26日

相关文章

  • intellitrace调试

    intellitrace调试 简介 Intellitrace是Visual Studio的一个调试工具,它提供了能够记录应用程序在运行时的状态变化的能力,可以捕获和保存以前运行过的调试会话信息,以便在后期调试时能够重现这些信息以精确地排查问题。Intellitrace调试可有效节省开发者调试成本和时间,特别适用于debug复杂逻辑的问题。 使用步骤 打开Vi…

    其他 2023年3月28日
    00
  • jsjson转字符串

    以下是详细讲解“JS中JSON转字符串的完整攻略”的标准Markdown格式文本: JS中JSON转字符串的完整攻略 在JavaScript中,可以使用JSON对象将JavaScript对象转换为JSON字符串。本文将介绍JSON对象的基本概念、使用方法和两个示例说明。 1. JSON对象基本概念 JSON(JavaScript Object Notatio…

    other 2023年5月10日
    00
  • 如何批量提取PDF文件名到excel表格?pdf文件名批量导入excel方法

    要将多个PDF文件名提取到Excel表格中,有几种不同的方法,可以根据具体情况选择最方便或最适合的方法: 1.使用命令行批量导出PDF文件名 Windows系统的命令行可以通过dir命令列出文件夹中的所有PDF文件名,然后将结果导出到TXT文档,最后用Excel打开文档并导入数据。 下面是详细步骤: 1.打开Windows的命令提示符,并用cd命令导航到包含…

    other 2023年6月26日
    00
  • Win10如何使用PowerShell批量替换文件名

    以下是关于Win10如何使用PowerShell批量替换文件名的完整攻略: 1. 如何打开PowerShell 在Win10操作系统中,我们可以通过以下步骤打开PowerShell: 点击开始菜单,搜索“PowerShell”并回车,即可打开; 或者在资源管理器的地址栏中输入“powershell”并回车,也可以打开PowerShell。 2. 批量替换文件…

    other 2023年6月26日
    00
  • Java向上转型和向下转型的区别说明

    Java中的向上转型(upcasting)和向下转型(downcasting)是针对于基础数据类型之外的类和对象而言的。 向上转型 向上转型是指从一个子类引用转换为其父类引用的过程,这种转化是自动完成的。在向上转型的过程中,实际所指向的对象为子类对象,但只能使用父类中定义的方法和属性。 下面是一个示例: public class Animal { publi…

    other 2023年6月26日
    00
  • H3C IRF2的技术原理及典型应用

    H3C IRF2技术原理及典型应用攻略 技术原理 H3C IRF2技术(Intelligent Resilient Framework)是一种可应用于大规模接入、汇聚网络的创新技术。该技术将多台网络设备(最多支持9台)虚拟成一个单一、可管理、可扩展的逻辑设备,成为网络内的一个“大的盒子”,并能够对外提供通用的网络服务。IRF2技术的核心思想是通过不同节点设备…

    other 2023年6月27日
    00
  • SpringBoot读取properties文件配置项过程解析

    SpringBoot读取properties文件配置项过程解析 在SpringBoot中,我们可以通过 .properties 文件来配置应用的相关参数,这些配置项可以用来设置一些基本的参数,比如应用所使用的数据库信息、日志级别、端口号等等。 配置文件位置 在SpringBoot应用程序中,配置文件的位置默认情况下是在 src/main/resources …

    other 2023年6月25日
    00
  • Microsoft Office 2007 SP1 简体中文正式版 升级包官方下载地址

    Microsoft Office 2007 SP1 简体中文正式版 升级包官方下载地址攻略 Microsoft Office 2007 SP1 简体中文正式版 升级包是用于更新 Microsoft Office 2007 到 Service Pack 1 版本的官方升级包。下面是详细的攻略,包括下载地址和示例说明。 下载地址 你可以通过以下步骤获取 Micr…

    other 2023年8月4日
    00
合作推广
合作推广
分享本页
返回顶部