iOSの音声認識(SFSpeechRecognizer)をObjective-Cで


iOSの音声認識をObjective-Cで

Swiftの記事は見つかるが、Objective-Cで書いてある記事がみつからなかったので書いておきます。

Swiftはこちら
http://dev.classmethod.jp/smartphone/iphone/try-ios10-speech-recognizer/

ユーザに許可を求める

hoge.m
  [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
  }];

変数定義

SpeechRecognizerManager.m
@interface SpeechRecognizerManager()
{
  SFSpeechRecognizer* speechRecognizer;
  SFSpeechAudioBufferRecognitionRequest* speechRequest;
  SFSpeechRecognitionTask* recognazationTask;
  AVAudioEngine *audioEngine;
}
@end

各種メソッド

SpeechRecognizerManager.m
-(SpeechRecognizerManagerIOS*)init
{
  audioEngine = [[AVAudioEngine alloc]init];
  if( audioEngine.inputNode ){
    [audioEngine.inputNode installTapOnBus:0 bufferSize:1024 format:nil block:^(AVAudioPCMBuffer* buffer, AVAudioTime* when) {
      [speechRequest appendAudioPCMBuffer:buffer];
    }];
  }
  speechRecognizer = [[SFSpeechRecognizer alloc]initWithLocale:[NSLocale localeWithLocaleIdentifier:@"ja-JP"]];
  speechRecognizer.delegate = self;
  speechRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
  speechRequest.shouldReportPartialResults = YES;

  return self;
}

-(void)start
{
  [audioEngine prepare];
  [audioEngine startAndReturnError:nil];

  recognazationTask = [speechRecognizer recognitionTaskWithRequest:speechRequest resultHandler:^(SFSpeechRecognitionResult *result, NSError * error) {
    if( result ){
      // ここで認識できた文字列が取得できる
      NSLog(@"%@", result.bestTranscription.formattedString);
    }
  }];

}
-(void)stop
{
  [audioEngine stop];
  [speechRequest endAudio];

  [recognazationTask cancel];
  recognazationTask = nil;
}