
一、前言
前一段時間彩云小譯上了App Store的推薦,我下載試玩了一下,效果還是非常不錯的。它可以實(shí)現(xiàn)實(shí)時翻譯的功能,我自己粗淺地分析了一下彩云小譯的實(shí)現(xiàn)原理,其中最重要的一步就是聲音轉(zhuǎn)文字。
目前市面上也有很多服務(wù)商提供聲音轉(zhuǎn)文字的服務(wù),有收費(fèi)的有免費(fèi)的,但是畢竟是第三方的服務(wù)商,接口的性能和穩(wěn)定性都不一定能保證。
2016年Apple在發(fā)布重磅產(chǎn)品iOS10的同時也發(fā)布了Speech Kit語音識別框架,大名鼎鼎的Siri的語音識別就是基于Speech Kit實(shí)現(xiàn)的。有了Speech Kit,我們就可以非常簡單地實(shí)現(xiàn)聲音轉(zhuǎn)文字的功能。下面我就簡單介紹一下Speech Kit的用法。
二、實(shí)現(xiàn)
1、頁面布局
因?yàn)橹皇菍?shí)現(xiàn)一個Demo,頁面不需要多復(fù)雜,只需要在Storyboard上拖入兩個控件:一個UITextView用于展示聲音轉(zhuǎn)文字的結(jié)果,一個UIButton用于觸發(fā)語音識別,最好布置好約束即可。具體效果如下圖:

2、申請用戶權(quán)限
首先需要引入Speech Kit框架
#import <Speech/Speech.h>
申請權(quán)限非常簡單,在識別前(viewDidLoad:)加入以下代碼即可申請語音識別的權(quán)限:
- (void)viewDidLoad {
[super viewDidLoad];
// 請求權(quán)限
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
NSLog(@"status %@", status == SFSpeechRecognizerAuthorizationStatusAuthorized ? @"授權(quán)成功" : @"授權(quán)失敗");
}];
}
這時候運(yùn)行起來會崩潰,原因是在iOS10后需要在info.plist文件中添加麥克分和語音識別權(quán)限申請信息:
<key>NSSpeechRecognitionUsageDescription</key>
<string>請?jiān)试S語音識別</string>
<key>NSMicrophoneUsageDescription</key>
<string>請打開麥克風(fēng)</string>
運(yùn)行項(xiàng)目,會提示打開語音識別和打開麥克風(fēng)權(quán)限,至此我們已經(jīng)完成了權(quán)限的申請。
3、初始化語音識別引擎
添加以下代碼:
- (void)initEngine {
if (!self.speechRecognizer) {
// 設(shè)置語言
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
self.speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:locale];
}
if (!self.audioEngine) {
self.audioEngine = [[AVAudioEngine alloc] init];
}
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord mode:AVAudioSessionModeMeasurement options:AVAudioSessionCategoryOptionDuckOthers error:nil];
[audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
if (self.recognitionRequest) {
[self.recognitionRequest endAudio];
self.recognitionRequest = nil;
}
self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
self.recognitionRequest.shouldReportPartialResults = YES;
}
- 初始化
SFSpeechRecognizer時需要傳入一個NSLocle對象,用于標(biāo)識用戶輸入的語種,如"zh-CN"代表普通話,"en_US"代表英文。 -
AVAudioEngine是音頻引擎,用于音頻輸入。 - 利用
AVAudioSession對象進(jìn)行音頻錄制的配置。 - 在語音識別產(chǎn)生最終結(jié)果之前可能產(chǎn)生多種結(jié)果,設(shè)置
SFSpeechAudioBufferRecognitionRequest對象的shouldReportPartialResult屬性為YES意味著每產(chǎn)生一種結(jié)果就馬上返回。
4、啟動語音識別引擎
添加以下代碼:
- (void)startRecording:(UIButton *)recordButton {
[self initEngine];
AVAudioFormat *recordingFormat = [[self.audioEngine inputNode] outputFormatForBus:0];
[[self.audioEngine inputNode] installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
[self.recognitionRequest appendAudioPCMBuffer:buffer];
}];
[self.audioEngine prepare];
[self.audioEngine startAndReturnError:nil];
[recordButton setTitle:@"錄音ing" forState:UIControlStateNormal];
}
- 為
self.recordButton添加點(diǎn)擊事件。 - 設(shè)置音頻錄制的格式及音頻流回調(diào)的處理(把音頻流拼接到
self.recognitionRequest)。 - 開始錄制音頻。
- 修改按鈕文案。
5、重置語音識別引擎
添加以下代碼:
- (void)stopRecording:(UIButton *)recordButton {
[[self.audioEngine inputNode] removeTapOnBus:0];
[self.audioEngine stop];
[self.recognitionRequest endAudio];
self.recognitionRequest = nil;
[recordButton setTitle:@"錄音" forState:UIControlStateNormal];
}
- 為
self.recordButton添加點(diǎn)擊事件。 - 停止音頻錄制引擎。
- 停止識別器。
- 修改按鈕文案。
6、語音識別結(jié)果的回調(diào)
下面是語音識別器SFSpeechRecognizer的API描述:
// Recognize speech utterance with a request
// If request.shouldReportPartialResults is true, result handler will be called
// repeatedly with partial results, then finally with a final result or an error.
- (SFSpeechRecognitionTask *)recognitionTaskWithRequest:(SFSpeechRecognitionRequest *)request
resultHandler:(void (^)(SFSpeechRecognitionResult * __nullable result, NSError * __nullable error))resultHandler;
// Advanced API: Recognize a custom request with with a delegate
// The delegate will be weakly referenced by the returned task
- (SFSpeechRecognitionTask *)recognitionTaskWithRequest:(SFSpeechRecognitionRequest *)request
delegate:(id <SFSpeechRecognitionTaskDelegate>)delegate;
語音識別結(jié)果的回調(diào)有兩種方式,一種是delegate,一種是block,這里為了簡單,先采用block的方式回調(diào)。
初始化語音識別器SFSpeechRecognizer時添加以下代碼:
[self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
NSLog(@"is final: %d result: %@", result.isFinal, result.bestTranscription.formattedString);
if (result.isFinal) {
self.textView.text = [NSString stringWithFormat:@"%@%@", self.textView.text, result.bestTranscription.formattedString];
}
}];
7、識別音頻文件
添加以下代碼
- (IBAction)startRecognizing:(id)sender {
SFSpeechRecognizer *recognizer = [[SFSpeechRecognizer alloc] initWithLocale:[NSLocale localeWithLocaleIdentifier:@"zh_CN"]];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test.mp3" withExtension:nil];
SFSpeechURLRecognitionRequest *request = [[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
[recognizer recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
if (result.isFinal) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"識別結(jié)果" message:[NSString stringWithFormat:@"%@", result.bestTranscription.formattedString] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:confirm];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
- 初始化語音識別器
SFSpeechRecognizer。 - 獲取音頻文件路徑。
- 初始化語音識別請求
SFSpeechURLRecognitionRequest。 - 設(shè)置回調(diào)。
三、總結(jié)
本文章主要介紹了如何利用iOS系統(tǒng)自帶的Speech Kit框架實(shí)現(xiàn)音頻轉(zhuǎn)文字的功能,Speech Kit相當(dāng)強(qiáng)大,本文章只是非常簡單的介紹了錄音識別及音頻文件識別而已,大家有興趣可以深入研究,有問題也可以一起探討。
聲音轉(zhuǎn)文字的功能我們已經(jīng)實(shí)現(xiàn)了,下一步我們可以找到翻譯服務(wù)提供商的服務(wù),就可以實(shí)現(xiàn)一個簡易版的實(shí)時翻譯應(yīng)用了。
本文Demo:https://github.com/OuDuShu/SpeechTest
四、參考
http://swift.gg/2016/09/30/siri-speech-framework/
https://developer.apple.com/videos/play/wwdc2016/509/
https://developer.nuance.com/public/Help/DragonMobileSDKReference_iOS/Getting-started.html
https://www.raywenderlich.com/60870/building-ios-app-like-siri