问题
I am trying to integrate google cloud speech API in my demo app. What I am getting as result is below :
{
results {
alternatives {
transcript: "hello"
}
stability: 0.01
}
}
Code to get response :
[[SpeechRecognitionService sharedInstance] streamAudioData:self.audioData
withCompletion:^(StreamingRecognizeResponse *response, NSError *error) {
if (error) {
NSLog(@"ERROR: %@", error);
_textView.text = [error localizedDescription];
[self stopAudio:nil];
} else if (response) {
BOOL finished = NO;
//NSLog(@"RESPONSE: %@", response.resultsArray);
for (StreamingRecognitionResult *result in response.resultsArray) {
NSLog(@"result : %@",result);
//_textView.text = result.alternatives.transcript;
if (result.isFinal) {
finished = YES;
}
}
if (finished) {
[self stopAudio:nil];
}
}
}
];
My problem is, the response i am getting is not a proper JSON then how do i get the value of key transcript
? Any help would be appreciated. Thanks.
回答1:
For someone who is looking for this problem's solution :
for (StreamingRecognitionResult *result in response.resultsArray) {
for (StreamingRecognitionResult *alternative in result.alternativesArray) {
_textView.text = [NSString stringWithFormat:@"%@",[alternative valueForKey:@"transcript"]];
}
if (result.isFinal) {
finished = YES;
}
}
This is what i did to get the value for transcript
continuously.
回答2:
Here's the code that will solve your problem on Swift4/iOS11.2.5, enjoy!:
SpeechRecognitionService.sharedInstance.streamAudioData(audioData, completion:
{ [weak self] (response, error) in
guard let strongSelf = self else {
return
}
if let error = error {
print("*** Streaming ASR ERROR: "+error.localizedDescription)
} else if let response = response {
for result in response.resultsArray {
print("result i: ") //log to console
print(result)
if let alternative = result as? StreamingRecognitionResult {
for a in alternative.alternativesArray{
if let ai = a as? SpeechRecognitionAlternative{
print("alternative i: ") //log to console
print(ai)
if(alternative.isFinal){
print("*** FINAL ASR result: "+ai.transcript)
strongSelf.stopGoogleStreamingASR(strongSelf)
}
else{
print("*** PARTIAL ASR result: "+ai.transcript)
}
}
}
}
else{
print("ERROR: let alternative = result as? StreamingRecognitionResult")
}
}
}
})
来源:https://stackoverflow.com/questions/42062099/google-cloud-speech-api-response-parsing-ios