1.项目中添加权限
Privacy - Speech Recognition Usage Description : 需要语音识别权限才能实现语音转文字功能

2.添加头文件
#import <AVFoundation/AVFoundation.h>
#import<Speech/Speech.h>

3.实现语音转文字逻辑:
3.1 根据wav语音文件创建请求
objectivec
SFSpeechURLRecognitionRequest *recognitionRequest
= [[SFSpeechURLRecognitionRequest alloc] initWithURL:[NSURL fileURLWithPath:wavFilePath]];
3.2 创建语言配置
objectivec
SFSpeechRecognizer *recongnizer
= [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
3.2 根据请求和语言配置创建任务,同时设置代理<SFSpeechRecognitionTaskDelegate>对象为自己
objectivec
SFSpeechRecognitionTask *task =
= [recongnizer recognitionTaskWithRequest:recognitionRequest delegate:self];
3.3 取消方法:
objectivec
[task cancel];
3.4 代理方法:
objectivec
// Called for all recognitions, including non-final hypothesis
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didHypothesizeTranscription:(SFTranscription *)transcription{
NSLog(@"转换中...");
}
// Called when recognition of all requested utterances is finished.
// If successfully is false, the error property of the task will contain error information
- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishSuccessfully:(BOOL)successfully{
NSLog(@"转换完成 是否成功:%d",successfully);
}
以上为针对单个语音文件转文字的整体逻辑
在实际使用中,会涉及到多条语音转文字,此时有一个环节需要注意:
当我们进行多条语音转文字时,可以将上述逻辑封装为一个一个类个体,每进行一条语音转文字时,创建一个对象进行处理
用多个对象来进行各自的语音转文字行为.
但是!!!这是行不通的.
因为即使每一个语音转文字逻辑是一个对象个体,但依然在未处理完当前的任务时,处理下一个语音转文字,会导致当前的语音转文字行为直接终止,并失败.
所以,针对这块儿,可以做成队列形式,也就是当有多个语音转文字的操作时,我们是可以将这多个任务添加到队列中,并依次执行.(这里队列是用数组方式实现)
最后展示实际代码截图


调用方式:


具体demo可以参考链接
https://gitee.com/huanxin666/EMDemo-oc
语音消息长按可显示出转文字的按钮,点击转文字即可进行转换
效果如下
Demo演示iOS语音转文字实现