9

我正在尝试将语音转换为文本并使用语音框架在 UILabel 中显示。我已授权用户允许使用麦克风。

这是我的代码

- (void)startRecording {
if (_recognitionTask != nil) {
[_recognitionTask cancel];
_recognitionTask = nil;
}

NSError *error;

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
[audioSession setMode:AVAudioSessionModeMeasurement error:&error];
[audioSession setActive:YES error:&error];

_recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
_recognitionTask = [[SFSpeechRecognitionTask alloc] init];

AVAudioInputNode *inputNode = [_audioEngine inputNode];

_recognitionRequest.shouldReportPartialResults = YES;

_recognitionTask = [_speechRecognizer     recognitionTaskWithRequest:_recognitionRequest resultHandler:^(SFSpeechRecognitionResult *result, NSError  *error) {
BOOL isFinal = NO;

if (result != nil) {
   _textLabel.text = [[result bestTranscription] formattedString];
   isFinal = result.isFinal;
}

NSLog(@"%@", error);

if (error != nil || isFinal) {
  _textLabel.text = [NSString stringWithFormat:@"%@", error];
  [inputNode removeTapOnBus:0];
  [_audioEngine stop];
  _recognitionRequest = nil;
  _recognitionTask = nil;
}
}];

[_audioEngine prepare];
[_audioEngine startAndReturnError:nil];
}

在调试时它进入了 recognitionTaskWithRequest 块,但结果为 nil 并且出现如下错误:

错误域=kAFAssistantErrorDomain 代码=203“损坏”UserInfo={NSUnderlyingError=0x14651450 {错误域=SiriSpeechErrorDomain 代码=102“(空)”},NSLocalizedDescription=Corrupt}

4

1 回答 1

2

问题是此代码缺少附加识别缓冲区的代码,因此要解决此问题,请在行前[_audioEngine prepare];添加以下代码

[_audioEngine.inputNode installTapOnBus:0 bufferSize:1024 format:[inputNode inputFormatForBus:0] block:^(AVAudioPCMBuffer *buffer, AVAudioTime *when){
                //NSLog(@"Tapped");
                [self.recognitionRequest appendAudioPCMBuffer:buffer];
            }];

这解决了我的问题。希望它也能帮助你。

于 2017-04-27T10:51:49.040 回答