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

SpeechRecognition簡介

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

功能授權

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

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

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

圖:

Paste_Image.png

基礎設置

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

@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;       // 用于展現的label
@property (nonatomic, weak) IBOutlet UIButton *startBtn;    // 啟動按鈕

在viewDidLoad中初始化,并判斷用戶授權是否通過

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

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

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

實現功能

點擊按鈕

- (IBAction)onStartBtnClicked:(id)sender
{
 if (self.currentSpeechTask.state == SFSpeechRecognitionTaskStateRunning)
   {   // 如果當前進程狀態是進行中
    
      [self.startBtn setTitle:@"Start Dictating" forState:UIControlStateNormal];
      // 停止語音識別
      [self stopDictating];
  }
   else
    {   // 進程狀態不在進行中
     [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)
    {
        // 識別結果,識別后的操作
        if (result == NULL) return;
        self.showLb.text = result.bestTranscription.formattedString;
    }];
}

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

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

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

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容