iOS10 ?Speech Recognition語音識別API的使用

SpeechRecognition簡介

iOS10中的公開的新API :Speech Recognition可以用于識別用戶的語音,我們可以根據(jù)識別結(jié)果來實現(xiàn)一些我們想要的操作。
網(wǎng)上搜羅了下相關(guān)資料不多,本人參考了一些國外的網(wǎng)站,自己寫了個DEMO,在這做個簡單分享:

功能授權(quán)

現(xiàn)在iOS10對系統(tǒng)功能的使用都需要進行一次用戶授權(quán),所以我們就像設置相機一樣,在info.plist文件中也要添加相關(guān)的使用描述,語音識別功能需要用到兩個系統(tǒng)功能:
NSSpeechRecognitionUsageDescription: 語音識別使用描述
NSMicrophoneUsageDescription:麥克風使用描述
所以我們添加:

<key>NSSpeechRecognitionUsageDescription</key> 
<string>Speech Recognition</string> 
<key>NSMicrophoneUsageDescription</key> 
<string>Microphone</string> 

這里的string即描述會在提示用戶的時候顯示。

圖:

Paste_Image.png

基礎設置

功能很簡單,點擊按鈕,開始聽寫,在label上顯示識別出的內(nèi)容

@property (nonatomic, strong) AVAudioEngine *audioEngine;                           // 聲音處理器
@property (nonatomic, strong) SFSpeechRecognizer *speechRecognizer;                 // 語音識別器
@property (nonatomic, strong) SFSpeechAudioBufferRecognitionRequest *speechRequest; // 語音請求對象
@property (nonatomic, strong) SFSpeechRecognitionTask *currentSpeechTask;           // 當前語音識別進程
@property (nonatomic, weak) IBOutlet UILabel *showLb;       // 用于展現(xiàn)的label
@property (nonatomic, weak) IBOutlet UIButton *startBtn;    // 啟動按鈕

在viewDidLoad中初始化,并判斷用戶授權(quán)是否通過

// 初始化
self.audioEngine = [AVAudioEngine new];
// 這里需要先設置一個AVAudioEngine和一個語音識別的請求對象SFSpeechAudioBufferRecognitionRequest
self.speechRecognizer = [SFSpeechRecognizer new];
self.startBtn.enabled = NO;

[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status)
{
    if (status != SFSpeechRecognizerAuthorizationStatusAuthorized)
    {
        // 如果狀態(tài)不是已授權(quán)則return
        return;
    }
    
    // 初始化語音處理器的輸入模式
    [self.audioEngine.inputNode installTapOnBus:0 bufferSize:1024
                                         format:[self.audioEngine.inputNode outputFormatForBus:0]
                                          block:^(AVAudioPCMBuffer * _Nonnull buffer,
                                                  AVAudioTime * _Nonnull when)
    {
        // 為語音識別請求對象添加一個AudioPCMBuffer,來獲取聲音數(shù)據(jù)
        [self.speechRequest appendAudioPCMBuffer:buffer];
    }];
    // 語音處理器準備就緒(會為一些audioEngine啟動時所必須的資源開辟內(nèi)存)
    [self.audioEngine prepare];
    
    self.startBtn.enabled = YES;
}];

注意: 如果你在info.plist文件中設置NSMicrophoneUsageDescription失敗,這時如果嘗試訪問_audioEngine.InputNode會使你的app崩潰,且你無法catch到有用的信息。

實現(xiàn)功能

點擊按鈕

- (IBAction)onStartBtnClicked:(id)sender
{
 if (self.currentSpeechTask.state == SFSpeechRecognitionTaskStateRunning)
   {   // 如果當前進程狀態(tài)是進行中
    
      [self.startBtn setTitle:@"Start Dictating" forState:UIControlStateNormal];
      // 停止語音識別
      [self stopDictating];
  }
   else
    {   // 進程狀態(tài)不在進行中
     [self.startBtn setTitle:@"Stop Dictaring" forState:UIControlStateNormal];
     self.showLb.text = @"I'm waiting";
        // 開啟語音識別
     [self startDictating];
    }
}

- (void)startDictating
{
   NSError *error;
  // 啟動聲音處理器
   [self.audioEngine startAndReturnError: &error];
   // 初始化
   self.speechRequest = [SFSpeechAudioBufferRecognitionRequest new];

    // 使用speechRequest請求進行識別
  self.currentSpeechTask =
  [self.speechRecognizer recognitionTaskWithRequest:self.speechRequest
                                    resultHandler:^(SFSpeechRecognitionResult * _Nullable result,
                                                    NSError * _Nullable error)
    {
        // 識別結(jié)果,識別后的操作
        if (result == NULL) return;
        self.showLb.text = result.bestTranscription.formattedString;
    }];
}

在這個方法中我們創(chuàng)建了一個新的識別請求和語音進程。當通過識別對象更新數(shù)據(jù)的時候,則更新label的text,無論聽寫是否仍然在進行中。
最后 我們只需要實現(xiàn)stopDictating:

- (void)stopDictating
{
    // 停止聲音處理器,停止語音識別請求進程
     [self.audioEngine stop];
     [self.speechRequest endAudio];
}

好了,代碼很少,很多東西也在注釋中寫明了,現(xiàn)在已經(jīng)可以實現(xiàn)聽寫的功能了。這時如果我們對識別的結(jié)果再進行一次判斷,根據(jù)不同的結(jié)果來執(zhí)行不同的操作,應該會有不錯的用戶體驗吧。

參考:http://gregshackles.com/using-speech-recognition-in-ios-10/?utm_source=tuicool&utm_medium=referral

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容