Search code examples
iosobjective-cspeech-recognitionsfspeechrecognizer

Proper way to use SFSpeechRecognizer?


I'm trying to use SFSpeechRecognizer but I don't have a way to test if I'm implementing it correctly, and since its a relatively new class i couldn't find a sample code (I don't know swift). Am I making any unforgivable mistakes/missing something ?

[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status){
    if (status == SFSpeechRecognizerAuthorizationStatusAuthorized) {
        SFSpeechRecognizer* recognizer = [[SFSpeechRecognizer alloc] init];
        recognizer.delegate = self;
        SFSpeechAudioBufferRecognitionRequest* request = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
        request.contextualStrings = @[@"data", @"bank", @"databank"];

        SFSpeechRecognitionTask* task = [recognizer recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult* result, NSError* error){
            SFTranscription* transcript = result.bestTranscription;
            NSLog(@"%@", transcript);
        }];
    }
}];

Solution

  • I´m trying too but this code works for me, after all SFSpeechRecognizer and SFSpeechAudioBufferRecognitionRequest are not the same, so I think (haven´t tested) you have to ask for different permissions (have you asked for permissions before? to use the microphone and the speechRecognition?). Ok here´s the code:

    //Available over iOS 10, only for maximum 1 minute, need internet connection; can be sourced from an audio recorded file or over the microphone
    
        NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:@"es-MX"];
            speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:local];
            NSString *soundFilePath = [myDir stringByAppendingPathComponent:@"/sound.m4a"];
            NSURL *url = [[NSURL alloc] initFileURLWithPath:soundFilePath];
            if(!speechRecognizer.isAvailable)
                NSLog(@"speechRecognizer is not available, maybe it has no internet connection");
            SFSpeechURLRecognitionRequest *urlRequest = [[SFSpeechURLRecognitionRequest alloc] initWithURL:url];
            urlRequest.shouldReportPartialResults = YES; // YES if animate writting
            [speechRecognizer recognitionTaskWithRequest: urlRequest resultHandler:  ^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error)
            {
        NSString *transcriptText = result.bestTranscription.formattedString;
                if(!error)
                {
            NSLog(@"transcriptText");
                }
            }];