ios – How get last Spoken word from SFSpeechRecognitionResult

I implement a speech recognition process to convert using SFSpeechRecognizer. Must implement deletion option to remove the last character. But SFSpeechRecognitionResult, result.bestTranscription.formattedString always returns an entire string from start to finish. Is there any way to get the last spoken word from SFSpeechRecognitionResult without stop & start recognition?

My implementation code

- (void)startListening{
// Initialize the AVAudioEngine
audioEngine = [[AVAudioEngine alloc] init];
_speechSynthesizer  = [[AVSpeechSynthesizer alloc] init];

// Make sure there's not a recognition task already running
if (recognitionTask)
    [_SFSpeechAudioBufferRecRequest endAudio];
    [audioEngine stop];
    // [recognitionTask cancel];
    // recognitionTask = nil;
// Starts an AVAudio Session
NSError *error;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
[audioSession setMode:AVAudioSessionModeMeasurement error:&error];
[audioSession setActive:true withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation  error:&error];

// Starts a recognition process, in the block it logs the input or stops the audio
// process if there's an error.
_SFSpeechAudioBufferRecRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
AVAudioInputNode *inputNode = audioEngine.inputNode;
_SFSpeechAudioBufferRecRequest.shouldReportPartialResults = YES;
recognitionTask = [speechRecognizer recognitionTaskWithRequest:_SFSpeechAudioBufferRecRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error)
    if (result)
        // Whatever you say in the microphone after pressing the button should be being logged
        // in the console.
    if (error)
        NSLog(@"ERROR %@", error);
            [audioEngine stop];
            [inputNode removeTapOnBus:0];
            _SFSpeechAudioBufferRecRequest = nil;
            recognitionTask = nil;
        @catch (NSException *exception)
            NSLog(@"EXCEPTION  ======== %@",exception);

// Sets the recording format
AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
[inputNode installTapOnBus:0 bufferSize:2048 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
    [_SFSpeechAudioBufferRecRequest appendAudioPCMBuffer:buffer];
// Starts the audio engine, i.e. it starts listening.
[audioEngine prepare];
[audioEngine startAndReturnError:&error];}

Thanks in advance!


Leave a Reply

Your email address will not be published.